Hi in DB i have four columns to store a time window. This would allow user to store 9:00 to 5:00 EST.
Now i need to parse this information in java.
java.sql.Time startTS = rs.getTime("begin_TIME ");
LocalTime localTime = startTS.toLocalTime();
offset could be made with: OffsetTime of(LocalTime time, ZoneOffset offset)
from what i see we cant convert zoneid to zoneoffset, so how do i 9:00 est(stored in time and zone columns) from sqlserver to java.
DB Table:
begin_TIME time NOT NULL,
begin_TIME_ZONE varchar(5) NOT NULL,
end_TIME time NOT NULL,
end_TIME_ZONE varchar(5) NOT NULL,
In the back-end I need to check that the request is in the window, request time is converted to ZonedDateTime and start and end need to come from DB:
public boolean compare(ZonedDateTime dateTime, OffsetTime startTime, OffsetTime endTime) {
OffsetTime offsetTime = dateTime.toOffsetDateTime().toOffsetTime();
int start = offsetTime.compareTo(startTime);
int end = offsetTime.compareTo(endTime);
return start >= 0 && end <= 0;
}
If I understand your situation right, this variant of your compare
method should be able to help you:
public boolean compare(ZonedDateTime dateTime, LocalTime start, ZoneId startTz,
LocalTime end, ZoneId endTz) {
ZonedDateTime startZonedDateTime = start.atDate(dateTime.toLocalDate()).atZone(startTz);
ZonedDateTime endZonedDateTime = end.atDate(dateTime.toLocalDate()).atZone(endTz);
return (! dateTime.isBefore(startZonedDateTime)) && (! dateTime.isAfter(endZonedDateTime));
}
I am using the date part of the supplied ZonedDateTime
to determine whether the comparison is to be made on a date where daylight saving time is in effect. I chose so because Java needs a date to be able to convert a local time to a zoned or offset time when the time zone may have daylight savings time.
It is possible to compare OffsetTime
(ignoring dates) objects as you do in your version, but I found it somewhat simpler to compare ZonedDateTime
objects instead. What it really does is compare the corresponding instants, so it works well even though the time zones differ.
I trust you to supply the two zone ID objects to the method. If you end up storing time zones as America/Toronto
in your database, this can be fed directly into ZoneId.of()
.
I really don't think you should stick to EST
and PST
. It's getting too complicated and errorprone. Java can translate EST
to -05:00
; this leaves you with no adjustment for daylight savings time (it does understand PST
as America/Los_Angeles
though). Use the modern forms America/Toronto
etc. See the answers to this question: How to tackle daylight savings using Timezone in java .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.