在 JavaScript 中创建 UTC 日期,添加一天,获取 unix 时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12413060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create UTC date in JavaScript, add a day, get unix timestamp
提问by dzm
I'm trying to build dates in UTC in JavaScript, while specifying an hour and minute then getting a timestamp of it.
我正在尝试在 JavaScript 中以 UTC 格式构建日期,同时指定一个小时和分钟,然后获取它的时间戳。
For example, If I have the hour of 15 and the minute of 25, I'm doing this:
例如,如果我有 15 小时和 25 分钟,我这样做:
var to_date = new Date();
to_date.setUTCHours(15);
to_date.setUTCMinutes(25);
var to_utc = new Date(to_date.getUTCFullYear(),
to_date.getUTCMonth(),
to_date.getUTCDate(),
to_date.getUTCHours(),
to_date.getUTCMinutes(),
to_date.getUTCSeconds());
var to_unix = Math.round(to_utc.getTime() / 1000);
console.log(to_unix);
The problem is this doesn't seem to be returning the right timestamp. It's setting the time not in UTC, but for my timezone. Any idea how to maintain this in UTC?
问题是这似乎没有返回正确的时间戳。它不是在 UTC 中设置时间,而是为我的时区设置时间。知道如何在 UTC 中维护它吗?
I also want to add a day to the time if it's past the current time. I've tried checking against the current and adding 60*60*24
, but this returned minutes/hours that didn't match what I specified.
如果超过当前时间,我还想为时间添加一天。我试过检查当前并添加60*60*24
,但这返回的分钟/小时与我指定的不匹配。
Any help would be great!
任何帮助都会很棒!
Thank you
谢谢
回答by josh3736
If you're tinkering with an existing date object:
如果您正在修改现有的日期对象:
var d = new Date();
d.setUTCHours(15);
d.setUTCMinutes(25);
d.setUTCSeconds(0);
d
will now represent today at 15:25 UTC.
d
现在将代表今天 15:25 UTC。
If you're starting from scratch:
如果您从头开始:
var d = new Date(Date.UTC(year, jsmonth, day, utchour, utcminute, utcsecond));
To get a unix timestamp, use getTime
, which returns the number of milliseconds since epoch UTC, then divide by 1000 to convert to unix time (which is in secondsrather than milliseconds):
要获取 unix 时间戳,请使用getTime
,它返回自 UTC 纪元以来的毫秒数,然后除以 1000 以转换为 unix 时间(以秒而不是毫秒为单位):
Math.round(d.getTime() / 1000);
Date.now()
gives you the current time in UTC since epoch in milliseconds. To add a day and see if it is in the future:
Date.now()
以毫秒为单位为您提供自纪元以来的当前 UTC 时间。添加一天并查看它是否在未来:
d.getTime() + (1000*60*60*24) > Date.now()
回答by Chase
回答by Anoop
Form link: The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes. Following should solve your problem
表单链接: getTimezoneOffset() 方法返回 UTC 时间和本地时间之间的时差,以分钟为单位。以下应该可以解决您的问题
var to_unix = Math.round( (Date.now() + (new Date().getTimezoneOffset()) ) / 1000);
console.log(to_unix);