Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a date object from string in javascript [duplicate]

Having this string 30/11/2011. I want to convert it to date object.

Do I need to use :

Date d = new Date(2011,11,30);   /* months 1..12? */ 

or

Date d = new Date(2011,10,30);   /* months 0..11? */ 

?

like image 683
Bader Avatar asked Nov 22 '11 09:11

Bader


People also ask

How do you convert a string to a Date in JavaScript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . 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.

Which is the correct way to create a Date object in JavaScript?

The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.

How convert dd mm yyyy string to Date in JavaScript?

To convert a dd/mm/yyyy string to a date:Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.


2 Answers

var d = new Date(2011,10,30); 

as months are indexed from 0 in js.

like image 138
Dogbert Avatar answered Sep 29 '22 18:09

Dogbert


You definitely want to use the second expression since months in JS are enumerated from 0.

Also you may use Date.parse method, but it uses different date format:

var timestamp = Date.parse("11/30/2011"); var dateObject = new Date(timestamp); 
like image 31
Igor Dymov Avatar answered Sep 29 '22 20:09

Igor Dymov