strip time from timestamp

后端 未结 3 1922
没有蜡笔的小新
没有蜡笔的小新 2021-01-23 18:50

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         


        
3条回答
  •  没有蜡笔的小新
    2021-01-23 19:25

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

    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)
    

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

提交回复
热议问题