new Date(1970, 0, 1, 0, 0, 0, 0).getTime()
// Since 1970-01-01 is Epoch, you may expect ZERO
// but in fact the result varies based on computer's timezone
这不是一个问题,如果你真的想要的时间从纪元以来考虑你的时区。因此,如果您想获得当前 Date 的时间,甚至基于 计算机的时区的指定 Date 的时间,您可以继续使用此方法。
// Seconds since Epoch (Unix timestamp format)
new Date().getTime() / 1000 // local Date/Time since Epoch in seconds
new Date(2020, 11, 1).getTime() / 1000 // time since Epoch to 2020-12-01 00:00 (local timezone) in seconds
// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)
new Date().getTime() // local Date/Time since Epoch in milliseconds
new Date(2020, 0, 2).getTime() // time since Epoch to 2020-01-02 00:00 (local timezone) in milliseconds
// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)
Date.UTC(1970, 0, 1)
// should be ZERO in any computer, since it is ZERO the difference from Epoch
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime() // difference in milliseconds between your timezone and UTC
(new Date(1970, 0, 1).getTime() - timezone_diff)
// should be ZERO in any computer, since it is ZERO the difference from Epoch
因此,使用这种方法(或者减去差值) ,结果应该是:
// Seconds since Epoch (Unix timestamp format)
Date.UTC(2020, 0, 1) / 1000 // time since Epoch to 2020-01-01 00:00 UTC in seconds
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date(2020, 0, 1).getTime() - timezone_diff) / 1000 // time since Epoch to 2020-01-01 00:00 UTC in seconds
(new Date(2020, 11, 1).getTime() - timezone_diff) / 1000 // time since Epoch to 2020-12-01 00:00 UTC in seconds
// Milliseconds since Epoch (used by some systems, eg. JavaScript itself)
Date.UTC(2020, 0, 2) // time since Epoch to 2020-01-02 00:00 UTC in milliseconds
// Alternatively (if, for some reason, you do not want Date.UTC)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date(2020, 0, 2).getTime() - timezone_diff) // time since Epoch to 2020-01-02 00:00 UTC in milliseconds
// **Warning**: notice that MONTHS in JavaScript Dates starts in zero (0 = January, 11 = December)
const timezone_diff = new Date(1970, 0, 1).getTime()
(new Date().getTime() - timezone_diff) // <-- !!! new Date() without arguments
// means "local Date/Time subtracted by timezone since Epoch" (?)