Java – (simple) dateformat, allowing 24:00:00 and 00:00:00 as input

I've been looking for this, but I haven't succeeded so far Do you know if there is a "dateformat" ish class, which will allow me to use "00:00:00" and "24:00:00" as input parameters (they are midnight), but when it is called "gethour()", I will get 0 or 24?

Using "KK" only allows me to have a < 1:24 > range, and I'm looking for a < 0:24 > range format

Solution

The value 24:00 is not represented in Localtime because it is strictly part of the next day Considering that 24:00 can be expressed as a part of the local time model, the conclusion is that it will be very confusing in many use cases and will produce more errors than it solves

But in Java 24:00 is supported in time It can be parsed using standard formatting techniques, but smart or lenient mode must be used. See resolverstyle The default mode is smart, but datetimeformatter ISO_ LOCAL_ DATE_ The formtter constant on datetimeformatter such as time is in strict mode Therefore, ofpattern() defaults to smart mode:

static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");

LocalDateTime ldt = LocalDateTime.parse("2012-12-03T24:00",FORMATTER);
System.out.println(ldt);  // 2012-12-04T00:00

Note that this also applies to offsetdatetime and zoneddatetime The standard parser of instant supports 24:00, and there is no special formatter:

Instant instant = Instant.parse("2015-01-01T24:00:00Z");
System.out.println(instant);  // 2015-01-02T00:00:00Z

You can use withresolverstyle() to convert any formatter to smart or lenient mode, as follows:

DateTimeFormatter f = ...  // obtain a formatter somehow
DateTimeFormatter smartMode = f.withResolverStyle(ResolverStyle.SMART);

// for example
f = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withResolverStyle(ResolverStyle.SMART);

The second element supported is parseexcessdays() This allows you to get out of date when parsing time only:

static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

TemporalAccessor parsed = TIME_FORMATTER.parse("24:00");
LocalTime lt = LocalTime.from(parsed);
Period excessDays = parsed.query(DateTimeFormatter.parsedExcessDays());
System.out.println(lt + " + " + excessDays);  // 00:00 + P1D

Finally, pay attention to advanced users Theoretically, it should be able to write its own temporary implementation. It is a copy of Localtime, but supports 24:00 as a valid value Such a class, such as localtimewithendofday, can run with the formatter / parser without problems (and may be a good supplement to threeten extra)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>