Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map java.time.LocalTime with milliseconds to a java.sql.Time with miliseconds

How can I convert a java.time.LocalTime with fractions of second (micro/milli/nano) to a java.sql.Time?

I know that since 2.x version of spring-data-jpa those types (JSR310) have their custom converters that maps to legacy java.sql.Date and java.sql.Timestamp but i'm having a lot of problems with the fraction of a second part of a LocalTime.

like image 722
Daniel Castillo Avatar asked Oct 30 '25 13:10

Daniel Castillo


2 Answers

How to map java.time.LocalTime to a java.sql.Time

Here is one way to do it without using String as intermediate value.

java.time.LocalTime localTime = java.time.LocalTime.now();
long epochMilli = localTime.atDate(java.time.LocalDate.EPOCH)
                           .atZone(java.time.ZoneId.systemDefault())
                           .toInstant()
                           .toEpochMilli();
java.sql.Time sqlTime = new java.sql.Time(epochMilli);

System.out.println(localTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")));
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(sqlTime));

Output

22:28:22.104
22:28:22.104
like image 69
Andreas Avatar answered Nov 01 '25 02:11

Andreas


The fundamental problem is that a local time represents a particular time during the day:

e.g. 7:30pm

Not 7:30pm today or yesterday, or seventeen weeks from Sunday, just ... 7:30pm.

Whereas a java.sql.Time represents a particular time on a particular day.

Internally they're stored as a long which is the number of milliseconds before or after a particular date (IIRC 1 Jan 1970).

So to convert a LocalTime to a java.sql.Time you have to specify a particular day to which that Time will apply.

Have a look at LocalTime.atDate(LocalDate) which returns a LocalDateTime.

There doesn't seem to be a nice simple way to extract the milliseconds or net nanoseconds (since 1/1/1970 00:00:00)

Maybe try .toEpochSecond (requires a time zone to be specified) and then multiply that by either 1000 or 1000000 and write that to the DB and then read it back out (to see whether it worked).


Alternately:

You keep saying you don't want the date - I understand, but since the database doesn't, you could try storing localTime.toNanoOfDay.

It will interpret that as a time of the day on 1/1/1970.

like image 45
Rick Avatar answered Nov 01 '25 02:11

Rick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!