本文介绍了Javascript日期 - 只设置日期,忽略时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆对象,每个对象都有一个时间戳,我希望按日期分组到JSON对象中。最终目标是这样的:

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:

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 timestamp object and using:

var visitDate = new Date(parseInt(item.timestamp, 10));
visitDate.setHours(0);
visitDate.setMinutes(0);
visitDate.setSeconds(0);

..然后我用它作为JSON对象的名称存储。看起来很乱,我确信应该有一种更简单的做事方式。

..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.

建议/建议欢迎!!

推荐答案

或者,使用 .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?

在这里查看所有有趣的Date方法:

Check out all the fun Date methods here: MDN Docs

编辑:如果你希望将其保留为日期对象,只需执行以下操作:

If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString());

Date的构造函数非常聪明地解析字符串(虽然不是没有大量的警告,但这应该工作非常一致),所以拿旧日期并将其打印到没有任何时间的日期将产生与原始帖子相同的效果。

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.

这篇关于Javascript日期 - 只设置日期,忽略时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 22:41