In my java (actually, Android, but it's irrelevant here) project, the user can enter start and end time for some activity and the system automatically computes the duration. On button press, I use System.currentTimeMillis()
to get the current timestamp.
For reasons outside the scope of this question, I need to discard the date part of the timestamp and only store the time one. Easy, I thought, just divide by the number of milliseconds in a day and take the remainder:
long currentTimestamp = System.currentTimeMillis();
long timeOnly = currentTimeStamp % (1000 * 60 * 60 * 24);
This almost works - except it produces timestamp one hour off. Here's an example:
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US);
long currentTimestamp = System.currentTimeMillis();
long timeOnly = currentTimestamp % (1000 * 60 * 60 * 24);
System.out.println("Full value: " + timeFormat.format(currentTimestamp));
System.out.println("Time only: " + timeFormat.format(timeOnly));
This code prints:
Full value: 10:53 PM
Time only: 11:53 PM
Full value: 11:19 PM
Time only: 12:19 AM
While I can just subtract one hour from the timestamp, I want to actually understand the reason why this is happening.