user3098791
user3098791

Reputation: 39

JavaScript Date() returns the wrong time

My simple test:

var ds = "2018/2/28 15:59";
console.log(ds);
var da = Date(ds);
console.log(da);
ds = "2018-2-28 15:59";
console.log(ds);
var da = Date(ds);
console.log(da);

The results are

2018/2/28 15:59  
Thu Feb 01 2018 17:26:57 GMT+0800 (+08)  
2018-2-28 15:59  
Thu Feb 01 2018 17:26:57 GMT+0800 (+08)  

Even given the time "2018/2/28 15:59" is in a different time zone, it is still very puzzling as the minutes and seconds are different: 59:00 versus 26:57. Timezone differences are in multiples of 30 minutes.

Upvotes: 2

Views: 16090

Answers (4)

AuxTaco
AuxTaco

Reputation: 5181

In addition to zeropublix's answer (you forgot the new), your date strings are invalid. The proper way to encode "15 hours and 59 minutes past the midnight marking the beginning of the 28th day of February, 2018 CE" is "2018-02-28T15:59Z". Your system (and mine) might recognize "2018/2/28 15:59" as a valid date string, but that's implementation-dependent and prone to failure. The only format recognized in the specification is a simplification of ISO 8601.

Upvotes: 3

flx
flx

Reputation: 1578

You forgot to add new before Date().

This means you were just calling a function called Date() which (by default) retuns the current date and time.

var ds = "2018/2/28 15:59";
console.log(ds);
var da = new Date(ds);
console.log(da);
ds = "2018-2-28 15:59";
console.log(ds);
var da = new Date(ds);
console.log(da);


An addition to AuxTacos answer, the proper way to init. your date:

var da = new Date(2018, (2-1), 28, 15, 59); // x-1 because 0=Jan,1=Feb...
console.log(date);

Upvotes: 6

Chandrika
Chandrika

Reputation: 194

var da = Date(ds); here Date gives the current time even if you pass parameter.

try this.

var ds = "2018/2/28 15:59"; var da = new Date(ds);

which gives 2018-02-28T10:29:00.000Z

Upvotes: -1

Noriel
Noriel

Reputation: 218

I try this.

var ds = "2018/2/28 15:59"; 
var da = new Date(ds);

it gives me Date 2018-02-28T15:59:00.000Z. I got right time and date.

Upvotes: -1

Related Questions