有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (3) 个答案

  1. # 1 楼答案

    Why cannot I clear time from timestamm this way

    您在UTC中正确地清除了时间部分Date中的毫秒值始终与UTC中1970年1月1日午夜相关。但是,由于Date.toString()的工作方式(它总是使用系统本地时区),您不能用UTC显示它。注意Date本身没有时区的概念。自1970年1月1日UTC午夜以来,这是毫秒数

    “从时间戳中清除一个时间”的概念在没有指定你所说的时区的情况下是没有意义的,因为同一个时间戳在不同的时区会有不同的时间(甚至日期)

    老实说,我建议在任何重要的日期/时间工作中使用Joda Time。然后你可以创建一个LocalDate,它显然是为了表示“仅仅是一个日期”——而从Date(或Instant)到LocalDate的转换将使你很容易指定你想要使用的时区

  2. # 2 楼答案

    试试这个

    Calendar c = Calendar.getInstance();
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
    String strDate = df.format(c.getTime()));
    

    现在,这样你可以有另一个日期,然后比较它。。。。因为它们现在是字符串格式

  3. # 3 楼答案

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

    为了比较日期,我建议使用支持此功能的JodaTime和LocalDate

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

    注意:这将构造适用于默认时区的无时区LocalDates。只要您只谈论设置了机器默认时区的时区,就可以了。e、 g.假设你的时区为CEST,那么这对欧洲大部分地区来说都没问题


    使用内置的时间函数,您可以执行以下操作

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