Assuming that your input string is 01/01/2017 6:54 PM
: it has 18 characters. When you call charAt(23)
, it tries to get the character at position 23, which doesn't exist: the string has positions from zero (the first 0
) to 17 (the M
). If you try to get a position greater than that, it throws a StringIndexOutOfBoundsException
.
But you don't need to do all this string manipulation. If you have a string that represents a date in some format, and want to convert it to another format, all you need is:
- parse the original string to a date
- format this date to another format
So you need 2 different Joda formatter's (one for each step). But there's one additional detail.
The input has a date (01/01/2017
) and a time (6:54 PM
), and the output has a date (2017-01-01
), a time (18:54:00.000
) and the UTC offset (+0100
). So you'll have an additional step:
- parse the original string to a date
- add the
+0100
offset to the parsed date
- format this date to another format
With Joda-Time, this can be achieved with the following code:
import org.joda.time.DateTimeZone
import org.joda.time.LocalDateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.ISODateTimeFormat
val fmt = DateTimeFormat.forPattern("dd/MM/yyyy h:mm a")
// parse the date
val localDate = LocalDateTime.parse("01/01/2017 6:54 PM", fmt)
// add the +01:00 offset
val dt = localDate.toDateTime(DateTimeZone.forOffsetHours(1))
// format to ISO8601
print(ISODateTimeFormat.dateTime().print(dt))
The output will be:
2017-01-01T18:54:00.000+01:00
Note that the offset is printed as +01:00
. If you want exactly +0100
(without the :
), you'll need to create another formatter:
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
println(formatter.print(dt))
The output will be:
2017-01-01T18:54:00.000+0100