java从时间戳剥离时间
为什么我不能用这种方式清除时间戳中的时间:
one day == 24 * 3600 * 1000 == 86400000 milliseconds.
long ms = new Date().getTime(); //Mon Sep 03 10:06:59 CEST 2012
Date date = new Date(ms - (ms % 86400000));
为什么这是Mon Sep 03 02:00:00 CEST 2012
而不是Mon Sep 03 00:00:00 CEST 2012
# 1 楼答案
您在UTC中正确地清除了时间部分。
Date
中的毫秒值始终与UTC中1970年1月1日午夜相关。但是,由于Date.toString()
的工作方式(它总是使用系统本地时区),您不能用UTC显示它。注意Date
本身没有时区的概念。自1970年1月1日UTC午夜以来,这是仅毫秒数“从时间戳中清除一个时间”的概念在没有指定你所说的时区的情况下是没有意义的,因为同一个时间戳在不同的时区会有不同的时间(甚至日期)
老实说,我建议在任何重要的日期/时间工作中使用Joda Time。然后你可以创建一个
LocalDate
,它显然是为了表示“仅仅是一个日期”——而从Date
(或Instant
)到LocalDate
的转换将使你很容易指定你想要使用的时区# 2 楼答案
试试这个
现在,这样你可以有另一个日期,然后比较它。。。。因为它们现在是字符串格式
# 3 楼答案
为了比较日期,我建议使用支持此功能的JodaTime和LocalDate
注意:这将构造适用于默认时区的无时区LocalDates。只要您只谈论设置了机器默认时区的时区,就可以了。e、 g.假设你的时区为
CEST
,那么这对欧洲大部分地区来说都没问题使用内置的时间函数,您可以执行以下操作