Reputation: 1431
I'm trying to convert date string to epoch Day using Java8's LocalDate api. When I try to verify the conversion it is actually one day off!
Here is the test
const val DATE_PATTERN = "MMMM d, yyyy"
@Test
fun `parse handles different cases`(){
val case1 = "September 31, 2018"
val dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_PATTERN, Locale("en", "US"))
val date1: Long = LocalDate.parse(case1, dateTimeFormatter).toEpochDay()
val case1Res = LocalDate.ofEpochDay(date1).format(dateTimeFormatter)
assertEquals(case1, case1Res)
}
The assertion fails with
expected: <September 31, 2018> but was: <September 30, 2018>
Upvotes: 0
Views: 648
Reputation: 7288
The comments state that, indeed, there are 30 days in September. The reason this code does not raise an error when parsing an incorrect date is because the DateFormatter is lenient by default, meaning that you can pass in September 64, 2018 and it will happily parse it for you and produce a correct epoch date.
You can make the DateFormatter throw an error on incorrect dates by adding a strict resolver style, like so:
DateTimeFormatter
.ofPattern(DATE_PATTERN, Locale("en", "US"))
.withResolverStyle(ResolverStyle.STRICT)
This will result in the following error when parsing the specified date:
Text 'September 31, 2018' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {YearOfEra=2018, MonthOfYear=9, DayOfMonth=31},ISO of type java.time.format.Parsed
Upvotes: 3