Finding the day in seconds since epoch, modulus not working
-
10-12-2019 - |
Question
I have the following code to try and get the current day in seconds since epoch, by removing any seconds after 00:00:00 on any given day:
public void method(Date date) {
...
long dayDate = date.getTime() - (date.getTime() % 86400L);
...
}
For some reason, dayDate is simply being set to date.getTime(), and the mathematical operators are doing nothing here.
How would I go about fixing this?
Solution
Like Ignacio already pointed out, date.getTime()
returns the number of milliseconds since January 1st, 1970, so your line should have been:
long dayDate = date.getTime() - (date.getTime() % 86400000L);
Iif you are planning on creating a new Date
with dayDate
, make sure that it has the right timezone, e.g. it should be in the UTC/GMT timezone. Otherwise, strange things like this could happen:
Date epoch = new Date(0);
System.err.println(epoch);
which gives on my machine Thu Jan 01 01:00:00 CET 1970
because my dates are by default created in the CET (+1) timezone. So if you would use your code and you would create a new Date
instance by using the long you calculated, you would end up with a date not at 0:00 on that day, but at 1:00.
However, without immediately resorting to Joda Time (which may not be an option in your project), you can use a Calendar to get the number of seconds:
// Create the calendar and set the date.
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
// Set the hours, minutes, etc. to 0.
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
long dayDate = calendar.getTime();
OTHER TIPS
I'll recommend that you use Joda Time library. It has most of the functions related to date, time and calendar that you'll ever need.