userfb
userfb

Reputation: 545

Java time formatting

I have the method

public static void testDateFormat() throws ParseException {
    DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
    Date hora;
    hora=dateFormat.parse("00:00:01");
    System.out.println(hora.getHours()+" "+hora.getMinutes());
    System.out.println("Date "+hora);
    System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
}

The output is

0 0
Date Thu Jan 01 00:00:01 COT 1970
Seconds 18001

Why the number of seconds is 18001? I expected to get 1 second.

Upvotes: 2

Views: 87

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338171

The answer by Elliott Frisch is correct.

Time-Only

But if you are working with time-only without date or time zone, then use a date-time library that can handle that explicitly rather than hacking the java.util.Date class.

LocalTime

Use either the Joda-Time library or the java.time package in Java 8. Both offer a LocalTime class.

LocalTime localTime = LocalTime.parse( "00:00:01" );
int minuteOfHour = localTime.getMinuteOfHour();

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201399

Because your Date has a TimeZone that is not UTC. It is, in fact, COT - which is UTC-5. And 5*60*60 is 18000 (or your result, plus one second). To get the value you expect, you could call DateFormat#setTimeZone(TimeZone) like,

DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // <-- Add this.
Date hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));

Output is as you expect.

Edit As noted in the comments, Date#getTime() per the Javadoc

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

And your Date of

Thu Jan 01 00:00:01 COT 1970

is equivalent to

Thu Jan 01 00:05:01 UTC 1970

and thus you get the 5 hour difference.

Upvotes: 6

Related Questions