Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse String dd-MMM-yyyy to Date Object JavaScript without Libraries [duplicate]

For Example:

var dateStr = "21-May-2014";

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

Like, var strConvt = new Date(dateStr);

like image 631
Naresh Raj Avatar asked Feb 27 '14 04:02

Naresh Raj


People also ask

How to convert string to date in JavaScript in dd MMM yyyy format?

“javascript convert date to dd-mmm-yyyy” Code Answer's var mm = String(today. getMonth() + 1). padStart(2, '0'); //January is 0!

How do I convert a string to a date in TypeScript?

Use the Date() constructor to convert a string to a Date object in TypeScript, e.g. const date = new Date('2024-07-21') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

What does date parse do in Javascript?

The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.


1 Answers

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
like image 163
RobG Avatar answered Oct 08 '22 21:10

RobG