将JavaScript日期初始化为午夜的最佳方法是什么?

本文翻译自:What is the best way to initialize a JavaScript Date to midnight?

获取新Date()实例但在午夜设置时间的最简单方法是什么?


#1楼

参考:https://stackoom.com/question/GL1E/将JavaScript日期初始化为午夜的最佳方法是什么


#2楼

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

#3楼

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的到期日期。


#4楼

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)),
}

#5楼

Just going to add this here because I landed on this page looking for how to do this in moment.js and others may do too. 只是在这里添加这个,因为我登陆了这个页面,寻找如何在moment.js中执行此操作 ,其他人也可以这样做。

[Rationale: the word "moment" already appears elsewhere on this page so search engines direct here, and moment.js is 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: 文档:

http://momentjs.com/docs/#/manipulating/start-of/ http://momentjs.com/docs/#/manipulating/start-of/


#6楼

You can probably use 你可以使用

new Date().setUTCHours(0,0,0,0)

if you need the value only once. 如果您只需要一次该值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值