0

I'm trying to receive a string to a date. Here's an example of the string:

val date = "10/10/2016 12:00:00 AM" //format month/day/year

Now, I'd like to convert this string into a date. To do that, I'm trying to run the following:

val formatter = SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa")
var date = formatter.parse(date)

Whenever this code is running on devices running android 8, everything works out great. However, if I try to run in older devices (ex.: phones using Android 6), I end up with a ParseException:

Unparseable date: "10/10/2016 12:00:00 AM" (at offset 20)

I've noticed that removing the AM/PM characters (aa) from the string solves the parsing exception. Can someone please tell me what's going on here?

thanks

Regards, Luis

PS: the code runs without any problem in the emulator, but not in real devices

Luis Abreu
  • 4,008
  • 9
  • 34
  • 63
  • 2
    From here : https://developer.android.com/reference/java/text/SimpleDateFormat?hl=pt-br In the examples and patterns, they only use one 'a' char for the PM/AM marker, Could you try that ? – Marech Jun 01 '18 at 09:07
  • are you getting time from date picker or time picker ? – Umair Jun 01 '18 at 09:09
  • Getting the date from web service... Unfortunately, it was formatted to a string in the format I've shown... – Luis Abreu Jun 01 '18 at 09:52

1 Answers1

1

Try this :

val date = "10/10/2016 12:00:00 AM"
val formatter = SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.US)
var date = formatter.parse(date)

Got from here : https://developer.android.com/reference/java/text/SimpleDateFormat?hl=pt-br

Looks like they never use "aa" for "PM/AM" value but rather "a" or "aaa".

Also from this response : Unable to parse DateTime-string with AM/PM marker They recommend changing your default Locale To Locale.US if you have different symbols for PM/AM

Marech
  • 157
  • 12
  • Hello. That was my initial string... Since it wasn't working, I've tried using aa... – Luis Abreu Jun 01 '18 at 09:53
  • Did your using `Locale` : https://stackoverflow.com/questions/3618676/unable-to-parse-datetime-string-with-am-pm-marker ? – Marech Jun 01 '18 at 10:09