Derek Adair
Derek Adair

Reputation: 21935

date string formatting

The best way to take a string that is formated like...

YYYY-MM-DD

and make it appear like...

MM/DD/YYYY

The reason it is not a javascript date object is because I am working with massive amounts of data and these dates are being pulled from a database.

I see no need to convert it to a date object.

Upvotes: 3

Views: 774

Answers (4)

cjstehno
cjstehno

Reputation: 13994

By brute force you could do something like:

var old = '2010-02-03'.split('-');
var desired = old[1] + '/' + old[2] + '/' + old[0];

Saves the hassle of working with Date object.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532645

If you replace the dashes with slashes it will parse, then you can use the date functions to get the various components (or convert to string using one of the various toString() functions).

var date = new Date( Date.parse( old.replace(/-/g,'/') ) );
alert( date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() );

This has the advantage of being able to use the date as a date for calculations, not merely doing string formatting. If string formatting is all you need AND your date strings are always valid, then using @Guffa's substr method is probably the best way to handle it.

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95588

You can use a regular expression in JavaScript (assuming JS because your question is tagged as such):

var date = "2010-05-09";
var formatted = date.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})/, "$2/$3/$1")

What I like about this more than using substring is that it seems more apparent what is being done.

Upvotes: 1

Guffa
Guffa

Reputation: 700720

How about:

s.substr(5,2) + '/' + s.substr(8) + '/' + s.substr(0,4)

Upvotes: 4

Related Questions