1

I am getting a value for my time field in this format "10:30:00.000Z". I want to convert it to 10:30 AM/PM format. I'm trying to make use of SimpleDateFormat and parse it but I'm getting java.text.ParseException. Can someone help me on this?

Value of treatmentObject.getTime() = "10:30:00.000Z"

'''

if (treatmentObject.getTIME1() != null) {  
System.out.println("Treatment time is"+treatmentObject.getTIME1());  
time1 = toISO8601UTC(fromISO8601UTC(treatmentObject.getTIME1()));
System.out.println("Time1  is" + time1);  
}  

public static String toISO8601UTC(Date date) {
System.out.println("date is::" + date);
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("HH:mm:ss.SSSZZZZZ");
df.setTimeZone(tz);
System.out.println("String date is::" + df.format(date));
return df.format(date);
}  

public static Date fromISO8601UTC(String dateStr) {
System.out.println("dateStr is::" + dateStr);
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("hh:mm a");
df.setTimeZone(tz);
    try {
    System.out.println("parse dateStr is::" + df.parse(dateStr));
    return df.parse(dateStr);
    } catch (ParseException e) {
        System.out.println("Inside catch exception");
        e.printStackTrace();
    }
    return null;
}

'''

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Post your code as text in the question , not as an image of text – Joakim Danielson May 25 '19 at 06:40
  • I am not able to post the code, It is throwing some errors like indent code with 4 spaces. I have tried a lot but not able to get out of the error. – Kunduri Raj May 25 '19 at 06:41
  • 1
    Then try again, and yes code text should be indented 4 spaces – Joakim Danielson May 25 '19 at 06:42
  • Ok, I'll try but can you look at the image and tell me where I'm doing wrong? – Kunduri Raj May 25 '19 at 06:47
  • Why 5 Z in the format? – Joakim Danielson May 25 '19 at 06:56
  • I recommend you don’t use `SimpleDateFormat`, `TimeZone` and `Date`. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead use `DateTimeFormatter`, `ZoneId` and either `OffsetTime` or `LocalTime`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 25 '19 at 06:58
  • `OffsetTime.parse("10:30:00.000Z").format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.US))` yields `10:30 AM`. – Ole V.V. May 25 '19 at 07:02
  • 1
    I have added the code now Plz look into it – Kunduri Raj May 25 '19 at 07:14
  • Possible duplicate of [String to Date Conversion mm/dd/yy to YYYY-MM-DD in java](https://stackoverflow.com/questions/50405211/string-to-date-conversion-mm-dd-yy-to-yyyy-mm-dd-in-java) – Ole V.V. May 25 '19 at 08:58

1 Answers1

1

java.time

    String treatmentTimeString = "20:01:00.000Z";
    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
                    .withLocale(Locale.US);
    OffsetTime treatmentTime = OffsetTime.parse(treatmentTimeString);
    OffsetTime timeInUtc = treatmentTime.withOffsetSameInstant(ZoneOffset.UTC);
    String formattedTime = timeInUtc.format(timeFormatter);
    System.out.println("Treatment time: " + formattedTime);

Output from this snippet is:

Treatment time: 8:01 PM

I am using java.time, the modern Java date and time API. I am further exploiting the fact that your time string conforms with ISO 8601, the standard format the the java.time classes parse (and also print) as their default, that is, without any explicit formatter. For formatting I am using Java’s built-in localized format. In this way I am free from writing any format pattern string myself, which is otherwise always an error-prone task.

I am converting the parsed time to UTC. In the example this is not necessary because the Z in the example string indicates that it is already in UTC. Doing it regardless makes sure that you will also get the correct UTC time if one day you get a time string with a different offset.

Question: Can I use java.time on Android API level 21?

It is giving the expected output but the problem is, it works with minimum API Level 26. My minimum api level 21. So any workaround?

Yes, certainly, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

What went wrong in your code?

It seems you swapped the format you had and the format you wanted. You had 20:01:00.000Z and tried to parse it with a formatter with format pattern hh:mm a. This obviously failed with the exception you reported. After that you tried to format the Date you had expected to get from parsing with a formatter with format pattern HH:mm:ss.SSSZZZZZ. If you had got this far, you would have seen that it gave you 20:01:00.000+0000, so not 10:30 AM/PM format.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Ole, Thanks for your answer man. It is giving the expected output but the problem is, it works with minimum API Level 26. My minimum api level 21. So any workaround? – Kunduri Raj May 25 '19 at 11:18
  • Thanks for the question. I had not been aware that you were programming for Android. No big problem! What you need is ThreeTenABP, the Android backport of java.time. Please see my edit and the added links. – Ole V.V. May 25 '19 at 14:02