Peter K.
Peter K.

Reputation: 587

Javascript new date from month and year string

I bumped into a situation where I'm getting a string indicating only the month and year of a date, and I need to create a Date object out of it. If I pass just the string, e.g. "February 2020" into a Date constructor, I strangely get back the the day of the previous month, i.e. in this case 2020-31-01. Thus, I need to always add 1 day to get the proper month in the Date object.

Here is the code to replicate:

var date_str = "February 2020";
var dt = new Date(date_str)

console.log(dt)    // Returns : 2020-01-31T23:00:00.000Z (????)

dt.setDate(dt.getDate() + 1);

console.log(dt)   // Returns : 2020-02-01T23:00:00.000Z

Any idea what the logic is behind this rather strange behaviour, or do I miss something here?

Update

Have accepted the first answer as being relevant, thus the main question is solved. However, just to add to the confusion: the code snippet I included runs as described with node. Using EXACTLY the same logic in a Vue.js application return the correct Date. Very strange!

Upvotes: 3

Views: 687

Answers (3)

Jonathan
Jonathan

Reputation: 9151

"February 2020" is not a valid input according to the specification thus you should not rely on it to work.

You should convert your input to one that is according to spec and then decide whether you need local time or UTC.

Handling time(zones) is one of the hardest things in JavaScript and I strongly recommend that you do not try to reinvent the wheel here yourself as it is really easy to mess up. Libraries like momentjs can help you here.

Upvotes: 2

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5600

Use moment.js library, it will give perfect.

moment("February 2020").format('L')
"02/01/2020"

enter image description here

Upvotes: 1

Sreeraj_ms
Sreeraj_ms

Reputation: 551

Actually you are passing February 2020 into the date Constructor , and its assumes the

date as 1 February 2020 thus it give the output as its UTC date which may be previous

day depending on your region

Upvotes: 1

Related Questions