简体   繁体   中英

Change time in DateFormat on Android

I have date and time extracted from JSON in following format

2013-01-16T13:43:11

I need to convert it to local time of Pakistan and add 5 hours to that time so the result is like:

06:43 

How I can achieve this?

Assuming that "2013-01-16T13:43:11" is in GMT

String s = "2013-01-16T13:43:11";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = df.parse(s);
date = new Date(date.getTime() + 5 * 3600 * 1000);
String time = new SimpleDateFormat("HH:mm").format(date);

time will be in your local timezone, so if you are in Pakistan it will be OK

You can use SimpleDateFormat as below:

String strDate = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "hh:mm");
strDate = dateFormatter.format(yourDate);

Hope it helps.

java dateFormat is not threadsafe, use joda time lib instead:

Joda time lib download

you can use withZone method to change time with specific Timezone

DateTime userTime1 = new DateTime();
            DateTime eventRecordTime = new DateTime();
            userTime1 = DateTime.parse("2012-07-05T21:45:00+02:00");
            eventRecordTime = DateTime.parse((String) jo.get("start_time"));
            DateTimeZone dtz = userTime1.getZone();
            System.out.println(eventRecordTime.withZone(dtz).toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM