How to set joda LocalDateTime object at specified time with current and local summer savings and timezone information in java

I am trying to create a java.sql.Time object to query time types in an SQL database, but I am using joda to parse the string I get.

I tried several different approaches. This is my last.

protected Time startTime = null; protected static final String dateFormat = "HH:mm:ssZ"; protected static final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat); public TimeBetweenFilter(String fieldName, String type, String value) { super(fieldName, type, value); String [] times = value.split("\\|"); if(times.length == 2 && !times[0].isEmpty() && !times[1].isEmpty()){ try{ LocalDateTime current = LocalDateTime.now(); LocalDateTime timeFromEpoch= new LocalDateTime(formatter.parseDateTime(times[0])); startTime = new Time(timeFromEpoch.withDate(current.getYear(), current.getMonthOfYear(), current.getDayOfMonth()).toLocalTime().toDateTimeToday().getMillis()); }catch (Exception e){ ... } 

But the output is always 1 hour below the accepted input. For example, if you enter 10:30:00 in UTC, startTime should be 4:30:00 local time. But instead, I get 3:30.

solvable

 DateTime beginning = new DateTime(DateTimeZone.UTC).toDateMidnight().toDateTime().plus(DateTime.parse(times[0], formatter).getMillis()); startTime = new Time(beginning.getMillis()); 

Creates a new date this morning at midnight with the UTC time zone, then adds the UTC time of the day in milliseconds. Then it is converted to a java.sql.Time object.

+4
source share
1 answer

A LocalDateTime logically has no time zone or DST information. That the whole point is "local", but not any particular time zone. Two people in different time zones can wake up with the same local date / time, but this does not mean that they are the same moments.

If you need a type that includes a timezone, you should use DateTime .

EDIT: Well, one approach is to take β€œtoday in the local time zone”, analyze the time before LocalTime , combine the two to form LocalDateTime , convert this to DateTime to UTC, then convert this DateTime value to the local time zone. The difficulty is that the end dates may not be the same, in which case you may need to add or subtract the day. Then this can change the time of day due to changes in the summer, which further complicates the situation. Unpleasant angular cases will probably be considered.

It looks like your requirement to start it oddly with the fact that it’s weird to have the time that is in UTC that you want to use in the date / time in the local time zone. Perhaps if you give some more context, this will help.

+3
source

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


All Articles