简体   繁体   中英

Localize time in Android

I am working on an Android application. User can send post and can see each other's post, pretty much like Twitter. Here's a issue with the time.

When server serialized timestamp from DB and send as response, it responses a String like this: 2011-09-01 13:20:30+00:00" Where I think the +00:00 part is UTC offset .

I was wondering what's a good approach to parse this string to some time object in local time zone? so I can show it correctly on UI?

Thanks!

您可以将其解析为日期对象,然后根据用户的区域设置使用SimpleDateFormatter对其进行格式化。

SimpleDateFormat has the capability of capturing your offset independently in a meaningful way. You want to translate the offset to a zone without explicitly specifying it to the parser instance.

Using SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssXXX");
try {
    System.out.println(sdf.parse(date));
} catch (ParseException e) {
    e.printStackTrace();
}

Gives,

Thu Sep 01 18:50:30 IST 2011

joda time library provides for an alternative resolution.

DateTimeFormatter is capable of parsing the format with Z added to the pattern and the parsed date is in the users default timezone .

DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ");
String date = "2011-09-01 13:20:30+00:00";

System.out.println(parser.parseDateTime(date));
System.out.println(parser.parseDateTime(date).toDate());

Gives,

2011-09-01T18:50:30.000+05:30
Thu Sep 01 18:50:30 IST 2011

You can pick any of the date formats above, modify it, further process it and use as part of your application.

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