JAVASCRIPT: Simple date conversion from SQL to readable


I needed a simple date converter function from SQL dates (YYYY-MM-DD) to something readable (M/D/YYYY).  So I wrote this little function.  Maybe someone else will have some use for it.

1
2
3
var makeSQLDatePretty = function(d) {
  return d.replace(/([0-9]{4})-0?([0-9]{1,2})-0?([0-9]{1,2})/, '$2/$3/$1');
};

Pass in a SQL date and the function trims leading zeros and returns a reformatted date.

1
2
var sqlDate = '2008-12-02';
alert(makeSQLDatePretty(sqlDate)); // should alert '12/2/2008'

Crazy Europeans may want to change the replace regex with ‘$3/$2/$1′.

Information and Links

Join the community by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
JAVASCRIPT: The start of a jQuery zoom event handler
JAVASCRIPT: Smart, unobtrusive AJAX form submission with jQuery

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!