将 JavaScript 日期初始化为午夜的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3894048/
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
What is the best way to initialize a JavaScript Date to midnight?
提问by Sixty4Bit
What is the simplest way to obtain an instance of new Date() but set the time at midnight?
获取 new Date() 实例但将时间设置在午夜的最简单方法是什么?
回答by CMS
The setHours
method can take optional minutes
, seconds
and ms
arguments, for example:
该setHours
方法可以采取可选的minutes
,seconds
和ms
参数,例如:
var d = new Date();
d.setHours(0,0,0,0);
That will set the time to 00:00:00.000
of your current timezone, if you want to work in UTC time, you can use the setUTCHours
method.
这会将时间设置00:00:00.000
为您当前的时区,如果您想在 UTC 时间工作,您可以使用该setUTCHours
方法。
回答by Dan
Just wanted to clarify that the snippet from accepted answer gives the nearest midnight in the past:
只是想澄清一下,接受答案的片段给出了过去最近的午夜:
var d = new Date();
d.setHours(0,0,0,0); // last midnight
If you want to get the nearest midnight in future, use the following code:
如果您想在未来获得最近的午夜,请使用以下代码:
var d = new Date();
d.setHours(24,0,0,0); // next midnight
回答by Zon
A one-liner for object configs:
对象配置的单行:
new Date(new Date().setHours(0,0,0,0));
When creating an element:
创建元素时:
dateFieldConfig = {
name: "mydate",
value: new Date(new Date().setHours(0, 0, 0, 0)),
}
回答by andyhasit
Just going to add this here because I landed on this page looking for how to do this in moment.jsand others may do too.
只是想在这里添加这个,因为我登陆这个页面寻找如何在moment.js 中做到这一点,其他人也可能这样做。
[Rationale: the word "moment" already appears elsewhere on this page so search engines direct here, and moment.jsis widespread enough to warrant to being covered going on how often it is mentioned in other date-related SO questions]
[理由:“时刻”这个词已经出现在这个页面的其他地方,所以搜索引擎直接指向这里,moment.js的广泛性足以保证在其他与日期相关的 SO 问题中提到它的频率]
So, in version 2.0.0 and above:
因此,在 2.0.0 及更高版本中:
date.startOf('day');
For earlier versions:
对于早期版本:
date.sod();
Docs:
文档:
回答by Stan
You can probably use
你可能可以使用
new Date().setUTCHours(0,0,0,0)
if you need the value only once.
如果您只需要一次该值。
回答by user3887038
If calculating with dates summertime will cause often 1 uur more or one hour less than midnight (CEST). This causes 1 day difference when dates return. So the dates have to round to the nearest midnight. So the code will be (ths to jamisOn):
如果使用夏季日期计算通常会导致比午夜 (CEST) 多 1 uur 或少 1 小时。当日期返回时,这会导致 1 天的差异。所以日期必须四舍五入到最近的午夜。所以代码将是(ths to jamisOn):
var d = new Date();
if(d.getHours() < 12) {
d.setHours(0,0,0,0); // previous midnight day
} else {
d.setHours(24,0,0,0); // next midnight day
}
回答by jamis0n
Adding usefulness to @Dan's example, I had the need to find the next midday or midnight.
为@Dan 的示例增加实用性,我需要找到下一个中午或午夜。
var d = new Date();
if(d.getHours() < 12) {
d.setHours(12,0,0,0); // next midnight/midday is midday
} else {
d.setHours(24,0,0,0); // next midnight/midday is midnight
}
This allowed me to set a frequency cap for an event, only allowing it to happen once in the morning and once in the afternoon for any visitor to my site. The date captured was used to set the expiration of the cookie.
这让我可以为一个事件设置一个频率上限,只允许它在早上和下午对我网站的任何访问者发生一次。捕获的日期用于设置 cookie 的过期时间。
回答by Mike
I have made a couple prototypes to handle this for me.
我已经制作了几个原型来为我处理这个问题。
// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('endOfDay', function () {
var date = new Date(this);
date.setHours(23, 59, 59, 999);
return date;
});
Date.method('startOfDay', function () {
var date = new Date(this);
date.setHours(0, 0, 0, 0);
return date;
});
if you dont want the saftey check, then you can just use
如果你不想要安全检查,那么你可以使用
Date.prototype.startOfDay = function(){
/*Method body here*/
};
Example usage:
用法示例:
var date = new Date($.now()); // $.now() requires jQuery
console.log('startOfDay: ' + date.startOfDay());
console.log('endOfDay: ' + date.endOfDay());
回答by Peemster
In case you already have d3.js as a dependency in your project, or don't mind bringing it in, d3-time(d3.js library is modular as of v4.0.0) has got Intervals.
如果您的项目中已经有 d3.js 作为依赖项,或者不介意引入它,d3-time(d3.js 库从 v4.0.0 开始是模块化的)有Intervals。
They might prove useful when setting dates to "default" values, e.g. midnight, 0.00 seconds, the first of the month, etc.
当将日期设置为“默认”值时,它们可能很有用,例如午夜、0.00 秒、一个月的第一天等。
var d = new Date(); // Wed Aug 02 2017 15:01:07 GMT+0200 (CEST)
d3.timeHour(d) // Wed Aug 02 2017 00:00:00 GMT+0200 (CEST)
d3.timeMonth(d) // Tue Aug 01 2017 00:00:00 GMT+0200 (CEST)