Proxy404
Proxy404

Reputation: 189

Efficiency in converting numeric date to textual

I have a date in the format MM/DD/YYYY. I need to then convert it into , using javascript. (More exact example: 05/25/2012 --> "May 25, 2012") I know how to convert the dates, but by question is:

Is there a more efficient way, whether using a javascript function or something else, to convert the MM/DD/YYYY to the format above instead of using a switch statement and concatenating strings?

Upvotes: 0

Views: 133

Answers (3)

matsev
matsev

Reputation: 33779

You may find the parseDate and formatDate functions in the Datepicker of jQuery UI appealing, e.g.

var date = $.datepicker.parseDate('mm/dd/yy', '05/25/2012');
$.datepicker.formatDate('MM d yy', date);

It all depends how you define 'efficient':

  • Code density? - This is efficient imho.
  • Speed and performance? - No clue.
  • Localization? - It is supported, e.g. $(selector).datepicker($.datepicker.regional['fr']);*

Upvotes: 1

savinger
savinger

Reputation: 6714

Strangely enough, I just posted a related question about half an hour ago. Here's what I'm using, but it also parses a time.

// Date m/d/Y Time h:m a
function parseDate(date,time) {

date = date.split("/");
time = time.split(" ");
hm = time[0].split(':'); 
if (parseInt(hm[0],10) == 12) {
    hm[0] = 0;
}
if (time[1] == 'pm') {
    hm[0] = parseInt(hm[0],10) + 12;
} else {
    hm[0] = parseInt(hm[0],10);
}
return new Date(
    parseInt(date[2],10), 
    parseInt(date[0],10)-1, 
    parseInt(date[1],10),
    hm[0],
    parseInt(hm[1],10)
);

}

So you could easily remove the time lines and have the following...

function parseDate(date) {

  date = date.split("/");

  return new Date(
    parseInt(date[2],10), 
    parseInt(date[0],10)-1, 
    parseInt(date[1],10)
  );

}

Upvotes: 0

John Hartsock
John Hartsock

Reputation: 86882

By accessing an array you could do this

var monthArray = ['January', 'February', ... , 'December'];


var date = "05/25/2012";

var dateParts = date.split('/');

var convertedDate = monthArray[parseInt(dateParts[0], 10)] + " " + dateParts[1] + ", " + dateParts[2];

Upvotes: 0

Related Questions