strip time from timestamp

2019-03-02 07:26发布

问题:

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

how come this is Mon Sep 03 02:00:00 CEST 2012 instead of Mon Sep 03 00:00:00 CEST 2012?

回答1:

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


回答2:

Why cannot I clear time from timestamm this way

You're correctly clearing the time part in UTC. The millisecond values in Date are always relative to January 1st 1970 midnight in UTC. However, you're not displaying it in UTC, because of the way Date.toString() works (it always uses the system local time zone). Note that a Date itself has no concept of a time zone. It's just a number of milliseconds since January 1st 1970 midnight UTC.

The concept of "clearing a time from a timestamp" doesn't really make sense without specifying which time zone you're talking about, as the same timestamp will have different times of day (and even dates) in different time zones.

To be honest, I would suggest using Joda Time for any significant date/time work. Then you can create a LocalDate which is obviously meant to represent "just a date" - and the translation from a Date (or Instant) to a LocalDate will make it easy for you to specify whichever time zone you want to use.



回答3:

Try this...

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

Now this way you can have the another date, and then compare it....as they are now in String format.