jeudi 25 février 2016

Android: Date is not being displayed as local time

I am trying to retrieve a date from a sqlite database and display it in a text view. In spite of using TimeZone.getDefault(), the time still shows up as GMT time, not the local time.

Here is the method where I try to convert the date to local time:

public String formatDate(String stringDate) {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
    try {
        Date date = sdf.parse(stringDate);
        TimeZone tz = TimeZone.getDefault();
        sdf.setTimeZone(tz);
        Log.v("formatDate", "TimeZone   " + tz.getDisplayName(false, TimeZone.SHORT) + " Timezon id :: " + tz.getID());
        return sdf.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return stringDate;
}

As you can see, I wanted to see if the timezone is actually the local time or not and added a log statement for that. Here is the output for the log statement:

02-25 15:15:55.422 29855-29855/com.example.ishita.assigntasks V/formatDate: TimeZone   GMT+05:30 Timezon id :: Asia/Calcutta

And here is the line where I call formatDate():

viewHolder.timeStamp.setText(formatDate(cursor.getString(cursor.getColumnIndex(TasksContract.MessageEntry.COL_AT))));

Please point out where I am going wrong and what I can do to display the date/time in the time zone where the device is being used.

Aucun commentaire:

Enregistrer un commentaire