5

For Example:

var dateStr = "21-May-2014";

I want the above to be into a valid Date Object.

Like, var strConvt = new Date(dateStr);

D3X
  • 547
  • 3
  • 20
Naresh Raj
  • 297
  • 1
  • 6
  • 18

1 Answers1

22

You need a simple parsing function like:

function parseDate(s) {
  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};
  var p = s.split('-');
  return new Date(p[2], months[p[1].toLowerCase()], p[0]);
}

console.log(parseDate('21-May-2014'));  //  Wed 21 May 00:00:00 ... 2014
RobG
  • 142,382
  • 31
  • 172
  • 209
  • RobG, thanks for your Response. I received a reply. Exactly what i wanted. – Naresh Raj Feb 27 '14 at 08:17
  • 1
    Really handy and concise. Behaved the same on IE, FF, and Chrome (which is *not* the case for Date.parse()). Interesting note: if you put in a slightly invalid date, such as '30-FEB-2019', it just counted into the next month, i.e., March 2, instead of throwing an exception. Could be a bonus or could be a harmful "corruption" depending on your situation, so FYI. – Justin May 16 '19 at 21:40