Convert joda LocalTime to sql Time

I want to convert a LocalTime object to a java.sql.Time object.

java.sql.Time time = new java.sql.Time(new LocalTime(1,0,0,0).getMillisOfDay()); System.out.println(time); //20:00:00 

In the above code, instead of creating a Time object with a value of 01:00:00, an object with a time of 20:00:00 is created. Local time is Eastern time.

What steps should I take?

+6
source share
4 answers

Time(..) takes a timestamp starting in 1970. Therefore, you should pass this:

new Time(new LocalTime(...).toDateTimeToday().getMillis())

+6
source

I believe that the currently accepted answer is incorrect. Although java.sql.Time implies that its date fields are set to 1970-1-1, this is not true. If you use conversion

 new java.sql.Time(new LocalTime(...).toDateTimeToday().getMillis()) 

then the internal millisecond representation of the java.sql.Time object will reflect today's date. This leads to unexpected behavior when comparing java.sql.Time objects. The comparison is performed on a millisecond value, and if the base dates are different, the time fields are not related to the result of the comparison.

The best method is to explicitly work with time fields using the deprecated constructor and methods in java.sql.Time:

 LocalTime localTime = new LocalTime(1,0,0,0); java.sql.Time sqlTime = new java.sql.Time(localTime.getHourOfDay(), localTime.getMinuteOfHour(), localTime.getSecondOfMinute()) 

Similarly in the other direction

 java.sql.Time sqlTime = new java.sql.Time(1,0,0); LocalTime localTime = new LocalTime(sqlTime.getHours(), sqlTime.getMinues(), sqlTime.getSeconds()); 
+6
source

It looks like a hole in the Joda Time API. getLocalMillis() is protected right now, but this is exactly the method I would like to use.

However, if you want to avoid obsolete methods, you can figure out the time on January 1, 1970:

 LocalTime lt = new LocalTime(1, 23, 45, 678); long millis = lt.toDateTimeToday().withDate(1970, 1, 1).getMillis() java.sql.Time time = new java.sql.Time(millis); 

It seems to work. Interestingly, I tried to calculate milliseeds by multiplying the field values. This created the correct long value, but when I passed it to the Time constructor, something strange happened to the timezone. (In my opinion, at least. The Time value ended five hours before I passed, and I am in the eastern daylight, so I think what happened.)

0
source

I found another way to convert java.time.LocalTime to java.time.LocalTime

 LocalTime localTime = LocalTime.now(); Time time = Time.valueOf(localTime); 
0
source

Source: https://habr.com/ru/post/909229/


All Articles