Javascript Date - 只设置日期,忽略时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11847806/
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
Javascript Date - set just the date, ignoring time?
提问by Paul
I have a bunch of objects, each of which has a timestamp, that I want to group by date, into a JSON object. The ultimate goal is something like this:
我有一堆对象,每个对象都有一个时间戳,我想按日期将它们分组到一个 JSON 对象中。最终目标是这样的:
myObject = {
"06/07/2012" : [
{
"timestamp" : "07/06/2012 13:30",
...
},
{
"timestamp" : "07/06/2012 14:00",
...
}
],
"07/07/2012 [...]
}
To get the date, I'm testing each timestampobject and using:
为了获取日期,我正在测试每个时间戳对象并使用:
var visitDate = new Date(parseInt(item.timestamp, 10));
visitDate.setHours(0);
visitDate.setMinutes(0);
visitDate.setSeconds(0);
..then I'm using that to store as a name for the JSON object. It seems messy, and I'm sure there should be an easier way of doing things.
..然后我用它来存储 JSON 对象的名称。这看起来很乱,我相信应该有一种更简单的做事方式。
Advice / suggestions welcomed!!
欢迎咨询/建议!!
回答by Nick
How about .toDateString()
?
怎么样.toDateString()
?
Alternatively, use .getDate()
, .getMonth()
, and .getYear()
?
另外,使用.getDate()
,.getMonth()
和.getYear()
?
In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?
在我看来,如果您想按日期对事物进行分组,您只需访问日期,而不是设置日期。通过设置访问日期字段的方式,您可以比较它们并将它们组合在一起,不是吗?
Check out all the fun Date methods here: MDN Docs
在此处查看所有有趣的 Date 方法:MDN 文档
Edit: If you wantto keep it as a date object, just do this:
编辑:如果要将其保留为日期对象,请执行以下操作:
var newDate = new Date(oldDate.toDateString());
Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.
Date 的构造函数在解析字符串方面非常聪明(虽然不是没有很多警告,但这应该非常一致),所以使用旧的 Date 并将其打印到没有任何时间的日期将导致与您在原帖。
回答by James Tomasino
If you don't mind creating an extra date object, you could try:
如果您不介意创建一个额外的日期对象,您可以尝试:
var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());
I do something very similar to get a date of the current month without the time.
我做了一些非常相似的事情来获取没有时间的当月日期。