Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toDateString() decrements my date

For the following code:

var d = new Date("2013-07-01");
console.log(d.toDateString());

It outputs Sun Jun 30 2013, which is one day less of what was input. What happened to the object? What date is actually stored?

like image 853
whileone Avatar asked Jul 31 '13 00:07

whileone


People also ask

What does toDateString do?

toDateString() method is used to convert the given date object's contents of date portion into a string. The date object is created using date() constructor.


3 Answers

The date is parsed as UTC date, but the toDateString() outputs what that time is in the local timezone.

Try this instead

var d = new Date(2013, 6, 1); //6 instead of 7 because the mont argument is  zero-based
console.log(d.toDateString());

What date is actually stored?

2013-07-01 00:00:00 UTC

like image 89
Esailija Avatar answered Nov 15 '22 15:11

Esailija


Parsing a Date from a string can yield different results depending on what browser/runtime you are using. There is a chart here that lists some of the browsers and what they support.

But in general, a string like "2013-07-01" is treated as if it were at midnight in UTC.

If you wanted to parse it in local time, you could use "2013/07/01". But that's a bit strange. You might be tempted to use "07/01/2013", but that might be interpreted as either Jan 7th or July 1st. Any of these are still implementation specific.

If you want a general purpose, "works everywhere" solution, you have a few different options:

Option 1

Don't parse it. Use the constructor that accept integers.

var d = new Date(2013,6,1);    // watch out for the zero-based month
console.log(d.toDateString());

// output:  "Mon Jul 01 2013"

With this code, the actual UTC time stored is going to vary depending on your own time zone. But since .toDateString() also takes that time into account, then you should be ok.

Option 2

Parse it as UTC, and display it as UTC/GMT:

var d = new Date("2013-07-01");
console.log(d.toUTCString());

// output:  "Mon, 01 Jul 2013 00:00:00 GMT"

But this output probably has more than you were looking for, and it may still look different in various browsers.

Option 3

Use the moment.js library, where you can control the formatting exactly however you desire.

var m = moment("2013-07-01", "YYYY-MM-DD");  // explicit input format
console.log(m.format("ddd MMM DD YYYY"));    // explicit output format

// output:  "Mon Jul 01 2013"

IMHO, this is the best solution. But it does require you use a library.

like image 42
Matt Johnson-Pint Avatar answered Nov 15 '22 14:11

Matt Johnson-Pint


Option 4

This approach works pretty good and doesn't require 3rd party libraries.

    var parts ='2013-07-01'.split('-');
    var mydate = new Date(Date.UTC(parts[0],parts[1]-1,parts[2])); //please put attention to the month
like image 38
Roman Podlinov Avatar answered Nov 15 '22 16:11

Roman Podlinov