在Android上将UTC转换为本地时间

时间:2021-12-30 21:49:10

In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.
I need to change this into Local time. That is where ever we use this the app needs to show the local time. How to I do this?

在我的项目中,我得到了json格式的API响应。我得到一个UTC时间格式的字符串值,如2013年7月16日上午12:08:59。我需要将其更改为本地时间。这就是我们使用此应用程序需要显示当地时间的地方。我该怎么做?

Here is some Code I have tried:

这是我尝试过的一些代码:

String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);

Assume aDate contains Jul 16, 2013 12:08:59 AM

假设aDate包含2013年7月16日上午12:08:59

5 个解决方案

#1


41  

Here's my attempt:

这是我的尝试:

String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);

Also notice the "a" for the am/pm marker...

还要注意am / pm标记的“a”...

#2


2  

//your UTC time var
long time = UTCtime;

//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));

//use the value
long localTime = timeFormat.toMillis(true);

#3


2  

I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.

我想提出现代的答案。虽然SimpleDateFormat是我们在2013年解析和格式化日期时间的类(除了Joda-Time),但它现在已经过时了,我们在java.time或JSR-310,现代Java日期和2014年Java 8推出的时间API。

But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.

但是我听到你说,大多数Android设备仍然没有运行Java 8。幸运的是,您仍然可以通过ThreeTenABP(JSR-310到Android Java 7的后端)使用现代Java日期和时间API。详细信息如下:如何在Android项目中使用ThreeTenABP。

Now the code is:

现在的代码是:

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
    String aDate = "Jul 16, 2013 12:08:59 AM";
    String formattedDate = LocalDateTime.parse(aDate, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.systemDefault())
            .format(formatter);
    System.out.println(formattedDate);

Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints

由于我的计算机正在运行欧洲/哥本哈根时区,该时区在7月比UTC早2小时,因此打印出来

Jul 16, 2013 02:08:59 AM

Further points:

更多要点:

  • Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.
  • 由于你的字符串中有AM,我假设你的小时数在AM之内,从1到12.要正确解析和格式化你需要格式模式字符串中的小写h。大写字母H表示从0到23的小时。
  • Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.
  • 更喜欢为formatter提供explcit语言环境(无论是SimpleDateFormat还是DateTimeFormatter)。如果没有给出语言环境,格式化程序将使用设备的默认语言环境。 “Jul”和“AM”是英文的,你的代码可以很好地运行在许多设备上,直到有一天它运行在具有非英语语言环境和崩溃的设备上,你很难搞清楚原因。
  • If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.
  • 如果可以,请明确给出所需的时区,例如ZoneId.of(“Asia / Kolkata”)。 JVM的默认时区可能会被程序的其他部分或在同一JVM中运行的其他程序更改,因此不可靠。

#4


1  

User the following code.

使用以下代码。

TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);

//Your Code
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);

This should work.

这应该工作。

#5


0  

1.Local to UTC Converter

1.本地到UTC转换器

public static String localToUTC(String dateFormat, String datesToConvert) {


        String dateToReturn = datesToConvert;

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setTimeZone(TimeZone.getDefault());
        Date gmt = null;

        SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
        sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));

        try {

            gmt = sdf.parse(datesToConvert);
            dateToReturn = sdfOutPutToSend.format(gmt);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateToReturn;
    }

2. UTC to Local Converter

2. UTC到本地转换器

public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {


    String dateToReturn = datesToConvert;

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date gmt = null;

    SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
    sdfOutPutToSend.setTimeZone(TimeZone.getDefault());

    try {

        gmt = sdf.parse(datesToConvert);
        dateToReturn = sdfOutPutToSend.format(gmt);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateToReturn; }

#1


41  

Here's my attempt:

这是我的尝试:

String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);

Also notice the "a" for the am/pm marker...

还要注意am / pm标记的“a”...

#2


2  

//your UTC time var
long time = UTCtime;

//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));

//use the value
long localTime = timeFormat.toMillis(true);

#3


2  

I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.

我想提出现代的答案。虽然SimpleDateFormat是我们在2013年解析和格式化日期时间的类(除了Joda-Time),但它现在已经过时了,我们在java.time或JSR-310,现代Java日期和2014年Java 8推出的时间API。

But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.

但是我听到你说,大多数Android设备仍然没有运行Java 8。幸运的是,您仍然可以通过ThreeTenABP(JSR-310到Android Java 7的后端)使用现代Java日期和时间API。详细信息如下:如何在Android项目中使用ThreeTenABP。

Now the code is:

现在的代码是:

    DateTimeFormatter formatter 
            = DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
    String aDate = "Jul 16, 2013 12:08:59 AM";
    String formattedDate = LocalDateTime.parse(aDate, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.systemDefault())
            .format(formatter);
    System.out.println(formattedDate);

Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints

由于我的计算机正在运行欧洲/哥本哈根时区,该时区在7月比UTC早2小时,因此打印出来

Jul 16, 2013 02:08:59 AM

Further points:

更多要点:

  • Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.
  • 由于你的字符串中有AM,我假设你的小时数在AM之内,从1到12.要正确解析和格式化你需要格式模式字符串中的小写h。大写字母H表示从0到23的小时。
  • Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.
  • 更喜欢为formatter提供explcit语言环境(无论是SimpleDateFormat还是DateTimeFormatter)。如果没有给出语言环境,格式化程序将使用设备的默认语言环境。 “Jul”和“AM”是英文的,你的代码可以很好地运行在许多设备上,直到有一天它运行在具有非英语语言环境和崩溃的设备上,你很难搞清楚原因。
  • If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.
  • 如果可以,请明确给出所需的时区,例如ZoneId.of(“Asia / Kolkata”)。 JVM的默认时区可能会被程序的其他部分或在同一JVM中运行的其他程序更改,因此不可靠。

#4


1  

User the following code.

使用以下代码。

TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);

//Your Code
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);

This should work.

这应该工作。

#5


0  

1.Local to UTC Converter

1.本地到UTC转换器

public static String localToUTC(String dateFormat, String datesToConvert) {


        String dateToReturn = datesToConvert;

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setTimeZone(TimeZone.getDefault());
        Date gmt = null;

        SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
        sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));

        try {

            gmt = sdf.parse(datesToConvert);
            dateToReturn = sdfOutPutToSend.format(gmt);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateToReturn;
    }

2. UTC to Local Converter

2. UTC到本地转换器

public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {


    String dateToReturn = datesToConvert;

    SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date gmt = null;

    SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
    sdfOutPutToSend.setTimeZone(TimeZone.getDefault());

    try {

        gmt = sdf.parse(datesToConvert);
        dateToReturn = sdfOutPutToSend.format(gmt);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateToReturn; }