0

I'm developing an app in which I'm saving the time when the post was posted.

I'm getting that time by using this code:

DateFormat currentTime = new SimpleDateFormat("h:mm a");
final String time = currentTime.format(Calendar.getInstance().getTime());

Now, what I want is I want to get user's timezone and convert the time saved in database using his/her timezone to his/her local time.

I tried doing this using code:

public String convertTime(Date d) {
    //You are getting server date as argument, parse your server response and then pass date to this method

    SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a");

    String actualTime = sdfAmerica.format(d);

    //Changed timezone
    TimeZone tzInAmerica = TimeZone.getDefault();
    sdfAmerica.setTimeZone(tzInAmerica);

    convertedTime = sdfAmerica.format(d);

    Toast.makeText(getBaseContext(), "actual : " + actualTime + "  converted " + convertedTime, Toast.LENGTH_LONG).show();
    return convertedTime;
}

but this is not changing the time.

This is how I'm trying to convert time saved in database using above method (postedAtTime is the time which is getting retrieved from database):

String timeStr = postedAtTime;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
Date date = null;
try {
    date = df.parse(timeStr);
} catch (ParseException e) {
    e.printStackTrace();
}
convertTime(date);

Please let me know what's wrong in my code or if this is wrong way?

guipivoto
  • 18,327
  • 9
  • 60
  • 75
Hammad Nasir
  • 2,889
  • 7
  • 52
  • 133

1 Answers1

1

The time string you're storing is not sufficient to be able to change timezones after the fact (h:mm a is only hours, minutes and am/pm marker). In order to do something like this you need to either store the timezone the original timestamp was in or better yet store the time in a deterministic manner like always UTC.

Example code:

    final Date now = new Date();
    final String format = "yyyy-MM-dd HH:mm:ss";
    final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
    // Convert to UTC for persistence
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    // Persist string to DB - UTC timezone
    final String persisted = sdf.format(now);
    System.out.println(String.format(Locale.US, "Date is: %s", persisted));

    // Parse string from DB - UTC timezone
    final Date parsed = sdf.parse(persisted);

    // Now convert to whatever timezone for display purposes
    final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US);
    displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));

    final String display = displayFormat.format(parsed);
    System.out.println(String.format(Locale.US, "Date is: %s", display));

Output

Date is: 2016-06-24 17:49:43
Date is: 13:49 PM -0400
Owais Ali
  • 724
  • 1
  • 6
  • 14