JustSystems Corporation strong> div>
In the question in this session, I was asked "How did you find these 10?" I knew it from the beginning, and I reviewed it when I did this session, but after all it is sober to read the source of Java core API or try something. I thought.
Today's topic
By the way, recently I suddenly became interested in the following, so I tried it.
Write a lot of H
We received responses from three people. Opinions were divided. I thought it was second.
But the reality was different.
Looking at the implementation of the core API, it looks like this. (Excerpt from 8u131 source)
java:DateTimeFormatterBuilder.java(LL.1793-1807)
case 'd':
case 'h':
case 'H':
case 'k':
case 'K':
case 'm':
case 's':
if (count == 1) {
appendValue(field);
} else if (count == 2) {
appendValue(field, count);
} else {
throw new IllegalArgumentException("Too many pattern letters: " + cur);
}
break;
Only 2 characters are accepted, so 3 or more characters are out.
So is it okay if there are two Hs? → In some cases, exceptions occur
So the next problem is this.
I thought this was also the second one.
But the reality was different.
I also saw the implementation.
java:Instant.java(LL.594-606)
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case NANO_OF_SECOND: return nanos;
case MICRO_OF_SECOND: return nanos / 1000;
case MILLI_OF_SECOND: return nanos / 1000_000;
case INSTANT_SECONDS: return seconds;
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}
The HOUR_OF_DAY
you are trying to get this time is ChronoField
, so the above
if (field instanceof ChronoField) {
It is included in this ʻifstatement to satisfy this condition. And since there is no corresponding field in
switch`, it means that it is out.
In other words, if you want to take some time, you have to have an instance of a class that supports HOUR_OF_DAY
such as LocalDateTime
. This was a learning experience.
appendix
Here is the code used for the test. Since I wrote it for personal use, there is no comment, and it is embarrassing to do it in a less beautiful way, such as switching between the two tests without commenting.
FormatterTest.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
*
*/
public class FormatterTest {
/**
*
* @param arguments
*/
public static void main(String[] arguments) {
//System.out.println(DateTimeFormatter.ofPattern("HH").format(Instant.now()));
System.out.println(DateTimeFormatter.ofPattern("HHHH").format(LocalDateTime.now()));
}
}