user2484678
user2484678

Reputation: 31

javascript date format using dateFormat String

I am working on Javascript dates, I have one date which is in the form of 20 Jun 13, I need to convert it into a Date Object, I used Date.parse() which returns 1 June 2013.

var frmDt = '20 Jun 13';
alert(Date.parse(frmDt));    

Which is the solution?

Upvotes: 1

Views: 182

Answers (3)

HMR
HMR

Reputation: 39270

I have taken the code posted in my comment and turned it into a function, made the jan,feb,mar case insensitie and the seperator character between day month year can be any character (as long is there is one). so any format dd mmm yy or dd/mmm/yy or d mmm yy will work:

function toDate(str){
    var months={
     "JAN":1,
     "FEB":2,
     //... other months
     "JUN":6,
     //... other months
     "DEC":12
    }
    var r=/^(\d{1,2}).(\w{3}).(\d{2}$)/;
    if(r.test(str)===false){
      throw new Error("Invalid date string:"+str);
    }
    var replaceFunction=function(){
     var years=parseInt(arguments[3],10);
     var m=months[arguments[2].toUpperCase()];
     if(typeof m==="undefined"){
       throw new Error("Invalid month name:"+arguments[2]);
     }
     var days=arguments[1]
     m=(m<9)?"0"+m:m;
     days=(days.length===1)?days="0"+days:days;
     years=(years>50)?years="19"+years:"20"+years;
     return m+"/"+days+"/"+years;
    };
    return new Date(str.replace(r,replaceFunction));
}
console.log(toDate("20 Jun 13"));

Upvotes: 0

user663031
user663031

Reputation:

d3.js has very robust capabilities for parsing and formatting dates. See https://github.com/mbostock/d3/wiki/Time-Formatting.

Upvotes: 0

Raibaz
Raibaz

Reputation: 9700

I found date handling in javascript made extremely easier by using momentJs, which allows you to construct moment objects that actually wrap native javascript Date objects in a very liberal way, passing in strings of many different formats and actually being able to get a date object, in a way that is way more reliable than Date.parse().

You can also pass in a date format string, so your case would be something like moment('20 Jun 13', 'DD MMM YY').

Upvotes: 1

Related Questions