4

I have a Date String which I am getting back from an API. The date is in this format.

2018-10-15T17:52:00Z

Now, I want to convert this string to UTC date format. This is the code I use for it,

private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";


 try {
        String expiryDateString = "2018-10-15T17:52:00Z";
        final SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT,Locale.US);
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        return formatter.parse(expiryDateString);
     } catch (final ParseException e) {
            return null;
     }

This method is returning the date as

Mon Oct 15 13:52:00 EDT 2018

I cannot use Java 8 functions. is there any way to convert string to UTC date time without using Java 8 methods?

Easy Coder
  • 277
  • 1
  • 3
  • 10
  • 1
    Visit https://stackoverflow.com/questions/4525850/java-convert-iso-8601-2010-12-16t133350-513852z-to-date-object – Chamila Lakmal Oct 15 '18 at 17:28
  • 1
    *"I want to convert this string to UTC date format"* That **is** UTC date format. The `Z` means UTC timezone. – Andreas Oct 15 '18 at 17:29
  • @Andreas how to convert this UTC date time string to proper UTC Date? – Easy Coder Oct 15 '18 at 17:40
  • 2
    Your code is already doing that, since a `java.util.Date` is always a UTC Date. The `EDT` time zone you see is applied when the UTC Date value is formatted for display. It is your displaying logic that is flawed, not the code in the question. – Andreas Oct 15 '18 at 17:45
  • 1
    Define Java 8 methods, please. Even on low API levels you *can* use java.time, the modern Java date and time API that first came out with Java 8. It has been backported, and the backport further adapted for Android. You need the ThreeTenABP library, see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). And you should want to because the `SimpleDateFormat` class you were using is not only long outdated, it is also notoriously troublesome. The modern API is so much nicer to work with. – Ole V.V. Oct 15 '18 at 19:18

1 Answers1

2

Mon Oct 15 13:52:00 EDT 2018

is the result of date.toString() - Date class.

The date is parsed correctly, just displayed differently. If you want to check that the parsing is correct you can check like this:

String expiryDateString = "2018-10-15T17:52:00Z";
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(expiryDateString);
assertEquals(expiryDateString, formatter.format(date));
Adina Rolea
  • 1,936
  • 1
  • 6
  • 15