Java has forbidden methods. You should never ever call them. If your IDE has the facility to generate warnings on any invocation of a method regardless of where it appears, add these methods to this list.
DateTimeFormatter.ofPattern(pattern) is one of them. It is forbidden. Do not use it.
The problem is, it presumes locale from your system. In your case, it has presumed the UK locale. Let's reverse the exercise:
LocalDateTime ldt = LocalDateTime.of(2021, 16, 2, 21, 11, 0);
System.out.println(ldt.format(DateTimeFormatter.ofPattern("MM/dd/yy hh:mm a", Locale.UK)));
>02/16/21 09:11 pm
// huh.
LocalDateTime ldt = LocalDateTime.of(2021, 16, 2, 21, 11, 0);
System.out.println(ldt.format(DateTimeFormatter.ofPattern("MM/dd/yy hh:mm a", Locale.ENGLISH)));
>02/16/21 09:11 PM
Well, look at that. Evidently, in british locale, AM/PM is written lowercase.
By default, DTF is case sensitive. That's all that's wrong here; if you try to parse with lowercase pm instead, it works fine. You can explicitly ask for case insensitive, but that's not the fix here. The locale might be chinese or japanese and perhaps a means something quite different there.
The real fix is to never call this method, and instead use the override where you explicitly specify the locale. That one is fine:
private fun extractTimestamp(date: String, time: String): Long {
val formatter = DateTimeFormatter.ofPattern("MM/dd/yy hh:mm a", Locale.ENGLISH)
return LocalDateTime.parse("$date $time", formatter)
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli()
}
The only thing I changed is that I added , Locale.ENGLISH in there.
Ocassionally you are faced with the need to actually go with the platform default, for example when rendering a time to the user. I strongly suggest you still skip these methods, instead making it explict by using Locale.getDefault(). Perhaps superfluous code, but in this case there is no question: That makes your code vastly easier to read by making clear that a default is being applied. It would have most likely meant you didn't have to write up a stack overflow answer, for example. Shorter code isn't always better code.