Use a formatter
Best to use a formatter:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now(ZoneId.of("Europe/Simferopol"));
String loadDate = dateTime.format(dtf);
System.out.println(loadDate);
When I ran this code just now I got:
2018-09-18 12:57:42
(and yes, the length is 19)
What went wrong in your code?
While LocalDateTime.now()
usually returns a date and time with millisecond or even microsecond precision depending on the platform, for example 2018-09-18T12:57:42.959829
, it may occasionally hit a whole minute. When this happens, the seconds and fraction of second are left out from the result of the toString
method, for example 2018-09-18T12:57
. This string has length 16. Trying to take a substring of the first 19 characters of a string of length 16 results in a StringIndexOutOfBoundsException
.
was this documented anywhere?
The documentation of LocalDateTime.toString
says:
The output will be one of the following ISO-8601 formats:
uuuu-MM-dd'T'HH:mm
uuuu-MM-dd'T'HH:mm:ss
uuuu-MM-dd'T'HH:mm:ss.SSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSS
uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS
The format used will be the shortest that outputs the full value of
the time where the omitted parts are implied to be zero.
We see that the first format has length 16 (all the others are 19 or longer).
For the sake of completeness, from the docs of String.substring(int, int)
(emphasis mine):
Throws:
IndexOutOfBoundsException
- if the beginIndex
is negative, or endIndex
is larger than the length of this String
object, or beginIndex
is larger than endIndex
.