Setsuna
Setsuna

Reputation: 2141

How to convert the following string to the correct string?

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

"25-AUG-11"

Upvotes: 1

Views: 179

Answers (6)

Mr_Green
Mr_Green

Reputation: 41832

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

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

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 :)

Upvotes: 2

RobG
RobG

Reputation: 147383

"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".

Upvotes: 0

icaru12
icaru12

Reputation: 1582

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"

Upvotes: 0

HMR
HMR

Reputation: 39260

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));

Upvotes: 0

EduardoSaverin
EduardoSaverin

Reputation: 545

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

Upvotes: 0

Related Questions