Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the TimeZone for String parsing in Android

I try to parse a String and set a time zone, but I can't produce the desired result.

String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = null;
try {
   date = readDate.parse(dtc);
   Log.d("myLog", "date "+date);
} catch (ParseException e) {
   Log.d("myLog", "dateExcep " + e);
}

SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm"); 
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00"));
String dateString = writeDate.format(date);

At the output of the variable "dateString" still gives the time 07:59:02 , and I want to make it +4 hours in advance that is 11:59:02

like image 484
Vlad Avatar asked Apr 02 '14 14:04

Vlad


People also ask

How do I set UTC time zone on Android?

Change your time zoneTap General. Tap Use device time zone on or off. If Use device time zone is on, your time zone will update automatically as you travel. If Use device time zone is off, you can select a time zone from the drop-down menu.

What is date format in Android Studio?

DateFormat. format("yyyy-MM-dd hh:mm:ss a", new java.


1 Answers

You need to instruct the read-formatter to interprete the input as UTC (GMT - remember that Z stands for UTC in ISO-8601-format):

String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
readDate.setTimeZone(TimeZone.getTimeZone("GMT")); // missing line
Date date = readDate.parse(dtc);
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00"));
String s = writeDate.format(date);

Then you will get:

02.04.2014, 11.59

like image 164
Meno Hochschild Avatar answered Sep 28 '22 07:09

Meno Hochschild