Converting joda LocalTime to sql Time

我只是一个虾纸丫 提交于 2019-12-08 19:35:56

问题


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

The above code, instead of creating a Time object with a value equal to 01:00:00, creates an object with a time of 20:00:00. The local time is eastern time.

What steps should I take?


回答1:


Time(..) accepts a timestamp starting from 1970. So you should pass that:

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




回答2:


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

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

then the internal millesecond representation of the java.sql.Time object will reflect today's date. This leads to unexpected behavior when comparing java.sql.Time objects. Comparisons are performed on the millisecond value, and if the underlying dates are different, the time fields are irrelevant to the comparison result

A better method, is to explicitly work with the 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());



回答3:


This seems like a hole in the Joda Time API. Right now getLocalMillis() is protected, but that's exactly the method I'd want to use.

However, if you want to avoid deprecated methods, you can figure out 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);

This seems to work. Interestingly, I tried figuring out the millis by multiplying the values of the fields out. That produced the right long value, but when I passed it to the Time constructor, something weird happened with the time zone. (I think, at least. The Time value ended up five hours before the value I passed in, and I'm on Eastern Daylight Time, so I think that's what happened.)




回答4:


i found another way to convert the java.time.LocalTime to java.time.LocalTime

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


来源:https://stackoverflow.com/questions/9422753/converting-joda-localtime-to-sql-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!