Fab
Fab

Reputation: 51

Java time problems

I have a problem of inconsistency with time objects

Time time1 =  new Time(72000000); //21:00
Time time2 = new Time(new Date().getTime()); //before 21 pm

time2.before(time1); 

The last line returns always false, why?

Upvotes: 4

Views: 179

Answers (4)

Nicky Jaidev
Nicky Jaidev

Reputation: 457

Seems that time1 is 14:00 . Run the below code snippet.

 Time time1 =  new Time(72000000); //21:00
 System.out.println(time1); //prints 14:00
 System.out.println(new Date());
 Time time2 = new Time(new Date().getTime()); //before 21 pm

Upvotes: 0

Nim
Nim

Reputation: 33655

This is not doing what you think it's supposed to do!

Time time1 =  new Time(72000000);

See this:

Time

public Time(long time)

Constructs a Time object using a milliseconds time value.

Parameters:
    time - milliseconds since January 1, 1970, 00:00:00 GMT; a negative number is milliseconds before January 1, 1970, 00:00:00 GMT

Now, hopefully you understand...

Upvotes: 1

Charles Forsythe
Charles Forsythe

Reputation: 1861

Since you didn't specify otherwise, I assume that the Time object is java.sql.Time.

This object uses a superclass of java.util.Date so it is actually a full date object. For the purposes of JDBC (SQL) it only concerns itself with the time portion of the date.

This:

Time time1 =  new Time(72000000);

...creates an object that represents 1-January-1970 21:00 hours. It will always be before any current time.

Upvotes: 0

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6361

Time:

A thin wrapper around the java.util.Date class that allows the JDBC API to identify this as an SQL TIME value. The Time class adds formatting and parsing operations to support the JDBC escape syntax for time values. The date components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed.

http://docs.oracle.com/javase/7/docs/api/java/sql/Time.html

Basically you're comparing 21:00 at the first of january 1970 to your current date at some point in the day. Obviously the former time happens earlier and is 'smaller'.

Upvotes: 2

Related Questions