简体   繁体   中英

Convert string to date in android the best way

什么是最好的方法,以及如何在Android中将此字符串“ 2015-07-18T13:32:56.971-0400”转换为日期并转换为用户手机的本地时区

I listed the duplicate link because you're asking how to parse a date string. That has been answered a gazillion times.

The other link shows that the user's phone's local timezone in android is the default timezone of the JVM, so you don't have to do any conversion.

To see for yourself, run the following code in any JVM (Android, PC, Mac, Linux, ...):

String input = "2015-07-18T13:32:56.971-0400";

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(input);
String output = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS a").format(date);
System.out.println(input + "  ->  " + output);

If you're in Los Angeles, CA, USA, you get this:

2015-07-18T13:32:56.971-0400  ->  07/18/2015 10:32:56.971 AM

Note that 13:32 was adjusted to 10:32 AM (10:32).

Just use these to get the time and date

public String getCurrentDate(){
    Time dtNow = new Time();
    dtNow.setToNow();
    return dtNow.format("%Y.%m.%d %H:%M");    // YYYYMMDDTHHMMSS
}

public String getCurrentTime(){
    Time dtNow = new Time();
    dtNow.setToNow();
    return dtNow.format("%H:%M");    // YYYYMMDDTHHMMSS
}

the first function will return time and the second function returns date

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