0

I have a timestamp coming from an API in this format:

yyyy-MM-dd'T'HH:mm:ss.SSSSSS

I want to format it for the user in their own timezone (on android). This is what I'm doing:

String timestampFromApi = "...";

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
Date date = df1.parse(timestampFromApi);

DateFormat df2 = new SimpleDateFormat();

Log.v(TAG, "In your timezone: " + df2.format(date));

But this prints the time in UTC. For example, if the timestamp happened at 4pm UTC time, and I am in PDT, the result is that it still prints "4pm".

I checked the timezone being used:

df2.getTimeZone()

and it does print out PDT for my device. What have I done wrong here?

Thanks

user3203425
  • 2,919
  • 4
  • 29
  • 48
  • your `df1.parse(timestampFromApi);` also uses PDT for timezone, therefore it does not know that the timezone on this timestamp is UTC. you need to `df1.setTimeZone(TimeZone.getTimeZone("UTC"))` first. – njzk2 Sep 22 '14 at 16:46
  • I had large problems with such conversions. Please try to use another Date implementation like DateTime from org.joda.time. It is much better than java.util.Date. – Tomek Sep 22 '14 at 16:55
  • possible duplicate of [Illegal pattern character 'T' when parsing a date string to java.Date](http://stackoverflow.com/questions/2597083/illegal-pattern-character-t-when-parsing-a-date-string-to-java-date). And [this](http://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date) and many others. Please search StackOverflow before posting. – Basil Bourque Sep 22 '14 at 17:20

1 Answers1

0

You're on the right track. You got the UTC time from the server, but now you just need to calculate the local offset when formatting. Try something like this:

private String formatTime(String timestampFromApi){
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
    df1.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = df1.parse(timestampFromApi);

    Log.v(TAG, "In your timezone: " + df1.format(getAdjustedTime(date.getTime())));
}

private Date getAdjustedTime(long utcDate){
    return new Date(utcDate + TimeZone.getDefault().getOffset(new Date().getTime()));
}

The getAdjustedTime() method will create a new Date object based on the UTC-offset from the local TimeZone.

Cruceo
  • 6,763
  • 2
  • 31
  • 52