从时间戳剥离时间 [英] strip time from timestamp

查看:167
本文介绍了从时间戳剥离时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能通过这种方式从时间戳中清除时间:

Why cannot I clear the time from a timestamp this way:

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

推荐答案


我实际上想将它与另一个未考虑时间的日期进行比较

I actually want to compare it to another date not taking into account time of day

为了比较日期,我建议使用JodaTime,它支持 LocalDate

To compare dates I suggest using JodaTime which supports this functionality with LocalDate

LocalDate date1 = new LocalDate(); // just the date without a time or time zone
LocalDate date2 = ....
if (date1.compareTo(date2) <=> 0)

注意:这将构建适合默认时区的无时区的LocalDates。只要您只谈论设置了机器默认时区的时区,就可以了。例如假设您的时区 CEST 那么这对欧洲大部分地区都没问题。

Note: this will construct timezone-less LocalDates which is appropriate for the default timezone. As long as you are only talking about the timezone where the default timezone for the machine has been set, this is fine. e.g. say you have a timezone of CEST then this is fine for most of Europe.

使用内置时间函数你可以做类似的事情

Using the built in time functions you can do something like

public static int compareDatesInTimeZone(Date d1, Date d2, TimeZone tz) {
    long t1 = d1.getTime();
    t1 += tz.getOffset(t1);
    long t2 = d2.getTime();
    t2 += tz.getOffset(t2);
    return Double.compare(t1 / 86400000, t2 / 86400000);
}

这篇关于从时间戳剥离时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆