1

What is the best way to convert the following string to a javascript date string format of MM/DD/YYYY?

"25-AUG-11"
Setsuna
  • 2,081
  • 7
  • 32
  • 50
  • SeeeeHeyaar - http://stackoverflow.com/questions/7151543/convert-dd-mm-yyyy-string-to-date – Caffeinated Jun 24 '13 at 02:28
  • 2
    Assuming you're not just referring to replacing the `-` with `/` - which is just a simple string manipulation - I tend to rely on my favorite, itty bitty js date plugin, [moment.js](http://momentjs.com/) for things like this. – jamesplease Jun 24 '13 at 02:41
  • 2
    @jmeas Why not give the one line moment.js parse/format expression as an answer? It certainly qualifies IMHO as the *best way* and I would upvote it as an answer. – Ray Toal Jun 24 '13 at 02:55

6 Answers6

2

The best way is that given by jmeans in the comment to the question.

When given a string representing a date in one format, then the "best way" to covert it to another format is to first parse it to a date, then format the date to the string you want.

Unless this is a one-time conversion, don't waste your time writing code to format and parse dates! This is a solved problem that is implemented by many thoroughly tested libraries. If you are doing anything that involves date handling and computation, doing things on your own can be error-prone.

One good lightweight date library is moment.js.

Include moment.js like this:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js"></script>

Then the JavaScript code for your particular example can be:

alert(moment("25-AUG-11", "DD-MMM-YY").format("MM/DD/YYYY"));

Live demo here

Note: Because you had "AUG" in your input string, you might need to tell the library to use English to parse the "MMM" part if your computer's locale does not use the English language.

Someday we will all speak ISO-8601. #rant :)

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • I disagree regarding "DO NOT waste your time writing code to format and parse dates". It's a simple task that, had the original used a four digit year, would take about 3 lines of code (and just a few lines more given a two digit year). – RobG Jun 24 '13 at 03:14
  • I definitely agree with this sentiment for a one-off, but in general I would never write an application that manipulates dates and the string-level. Regardless of ease or lines of code, that just reeks of mixing abstraction levels. I would even use the ugly built-in ECMAScript Date if it would work. Cheers. :) – Ray Toal Jun 24 '13 at 03:25
  • Unfortunately the built–in date object is pretty useless for parsing. If I was doing a lot of time and date stuff with formatting (say a calendar), I may use a date library, but not otherwise. But then, I much prefer to see an actual date and time rather than "about 10 minutes ago". – RobG Jun 24 '13 at 03:58
0

Use can use Date object method: ToISOString() This coverts date to string according to ISO standard OR Use :::toLocaleDateString()

EduardoSaverin
  • 545
  • 4
  • 19
0

You could use something like this:

var months={
 "JAN":1,
 "FEB":2,
 //... other months
 "DEC":12
}
var r=/(\d{1,2})\-(\w+)?\-(\d{1,2})/;
var replaceFunction=function(){
 var years=parseInt(arguments[3],10);
 var m=months[arguments[2]];
 var days=arguments[1]
 if(m<9){
   m="0"+m;
 }
 if(days.length===1){
   days="0"+days;
 }
 if(years>50){
   years="19"+years;
 }else{
   years="20"+years;
 }
 return m+"/"+days+"/"+years;
};

console.log("5-JAN-14".replace(r,replaceFunction));
console.log("25-FEB-98".replace(r,replaceFunction));
HMR
  • 37,593
  • 24
  • 91
  • 160
0

You can use this JavaScript function to achieve that:

function formatDate(dateparam) {
    var dateObj = new Date(Date.parse(dateparam));

    var date = dateObj.getDate();
    date = (date.toString().length == 1) ? "0" + date : date;

    var month = dateObj.getMonth() + 1;
    month = (month.toString().length == 1) ? "0" + month : month;

    var year = dateObj.getFullYear();

    return month + "/" + date + "/" + year;
}

document.write(formatDate("25-AUG-11"));
//returns "08/25/2011"
icaru12
  • 1,522
  • 16
  • 21
0

"Best" is relative and you haven't provided any criteria. Here's one way using plain string manipulation:

function reFormatDateString(s) {
  s = s.split('-');
  var months = {jan:'01', feb:'02', mar:'03', apr:'04',  may:'05',  jun:'06',
                jul:'07',  aug:'08',  sep:'09',  oct:'10',  nov:'11',  dec:'12'};
  return months[s[1].toLowerCase()] + '/' + s[0] + '/' + s[2];
}

alert(reFormatDateString('25-AUG-11')); // 08/25/2011

However, likely you want to deal with the two digit year more specifically.

// The format "MM/DD/YYYY" isn't a "javascript" format, it's a US format.
function reFormatDateString1(s) {
  s = s.split('-');
  var months = {jan:'01', feb:'02', mar:'03', apr:'04',  may:'05',  jun:'06',
                jul:'07',  aug:'08',  sep:'09',  oct:'10',  nov:'11',  dec:'12'};
  var m = +s[2];
  s[2] = m < 100? (m < 50? m + 2000 : m + 1900) : m;
  return months[s[1].toLowerCase()] + '/' + s[0] + '/' + s[2];
}

Here's another version that uses a date object:

function reFormatDateString2(s) {
  s = s.split('-');
  var months = {jan:0, feb:1, mar:2, apr:3,  may:4,  jun:5,
                jul:6,  aug:7,  sep:8,  oct:9,  nov:10,  dec:11};
  function z(n){return (n<10? '0' : '') + n;}

  // Convert 2 digit year. If < 50, assume 21st century,
  // otherwise assume 20th.
  // Adjust range to suit
  if (s[2].length == 2) {
    if (s[2] < 50 ) {
      s[2] = +s[2] + 2000;
    } else {
      s[2] = +s[2] + 1900;
    }
  }
  var d = new Date(s[2], months[s[1].toLowerCase()], s[0]);

  return z(d.getMonth() + 1) + '/' + z(d.getMonth()+1) + '/' + z(d.getFullYear());
}

You choose "best".

RobG
  • 142,382
  • 31
  • 172
  • 209
0

This seems to be working fine.

var date = new Date("25-AUG-11");
console.log(date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear());

Working Fiddle

You just need to add 0 at starting of month value which can be done easily with string length comparison.

Source

Mr_Green
  • 40,727
  • 45
  • 159
  • 271