开发者

Date javascript

开发者 https://www.devze.com 2023-01-13 20:12 出处:网络
I am trying to understand more about the Date object in javascript. I thought that when you call valueOf(), you get the amount of milliseconds since january 1, 1970.

I am trying to understand more about the Date object in javascript. I thought that when you call valueOf(), you get the amount of milliseconds since january 1, 1970. So what I would expect is that the following should return exactly zero;

alert((new Date(1970, 1, 1).valueOf() )/ ( 86400 * 1000));

but it does not, it returns 30.958333333333332. 开发者_开发技巧What am I missing?

gr,

Coen


new Date(1970, 1, 1) actually is Feb. Months are zero-indexed. Try changing it to new Date(1970, 0, 1).


Second parameter, month, starts with 0, so you need to do:

alert((new Date(1970, 0, 1).valueOf() )/ ( 86400 * 1000));

but even with this you'll get the offset, in seconds, off GMT.

the value you posted says you are GMT +1 : )


If you're looking to work with the unix epoch time, you have a few options

  • UTC() Returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time
  • setTime() Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
  • parse() Parses a date string and returns the number of milliseconds since midnight of January 1, 1970
  • getTime() Returns the number of milliseconds since midnight Jan 1, 1970

valueOf() returns a primitive of the value, I'd stay away from it and work with the above options.

source: http://www.w3schools.com/jsref/jsref_obj_date.asp.

edit: also, your asking for Feb 1, 1970

use this, it's dangerous to go alone:

var d=new Date(1970, 0, 1);
document.write(d.getTime());

or

var d= Date.parse("Jan 1, 1970"); //Note, we don't use NEW keyword.
document.write(d);

Remember, epcoh is Wed Dec 31 1969 19:00:00 GMT-0500. If you use .getTime() you'll see UTC time Thu, 01 Jan 1970 00:00:00 GMT +0000.


The method you are searching is .getTime() not .valueOf()


Months are zero based in Date objects.


January 1st, 1970 is new Date(1970, 0, 1), since months start at 0 = January.


The first of january 1970 with the Date object is new Date(1970, 0, 1)


it was the month that should have been 0 in combination with an hour difference from GMT

alert((new Date(1970, 0, 1, 1, 0, 0, 0).valueOf()));

produces 0

0

精彩评论

暂无评论...
验证码 换一张
取 消