Frej Alexander Nielsen Frej Alexander Nielsen - 1 month ago 11
Java Question

date.getTime() is shorter than System.getCurrentTimeMillis()

I'm trying to create a simple Alarm Clock, but I stumbled upon a problem that I can't seem to fix. I'm trying to parse a string to a date so I can get the difference between the current time and the time to set off the alarm.

Here's my code to parse the time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

Date date = sdf.parse(args[0]);

Here's my getTimezone() method:

public static TimeZone getTimezone() {
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);

String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
return TimeZone.getTimeZone(name);

And here's my code for figuring out the difference:

long diff = date.getTime() - System.currentTimeMillis();

So my problem is that the date.getTime() returns 79680000, while System.currentTimeMillis() returns 1473538047978 (This is of course different every time, but for some odd reason, date.getTime() is not).

Which means that I get a negative number when trying to figure out the difference, and therefore I cannot use it.

EDIT: After a little bit of debugging, I realised that it has to do with the year, month and day not being set, however I do not know how to get those.


You did notice that date.getTime() returns 79680000 which is 22 hours and 20 minutes after 1 January 1970. The problem is (as you noticed) that you did not parse year, month and day.

You can do it by:

SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY hh:mm:ss"); 

Example input 20/04/2016 20:20:0 returns time as Mon Jan 04 20:20:00 CET 2016 (don't look at the timezone). It is 1451935200000 miliseconds after 1 January 1970.

Note: change string to match your format requirements (the syntax is self-explanatory).