将时间更改为特定时区的最简单方法

时间:2012-09-13 22:36:52

标签: java android time timezone

有两个字符串

String date = "9/13/2012";
String time = "5:48pm";

时间是GMT + 0,我想把它改为GMT + 8,将时间改为特定时区的最简单方法是什么

3 个答案:

答案 0 :(得分:2)

  • 使用设置为UTC时区的SimpleDateFormat解析它
  • 使用设置为您感兴趣的时区的Date格式化已解析的SimpleDateFormat值。(它可能不仅仅是“UTC + 8” - 您应该找出哪个您真正想要的TZDB时区ID。

例如:

SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = inputFormat.parse(date + " " + time);

// Or whatever format you want...
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
outputFormat.setTimeZone(targetTimeZone);
String outputText = outputFormat.format(date);

(如果您可以使用Joda Time代替,那就太棒了 - 但我知道这对Android应用来说非常重要。)

答案 1 :(得分:1)

Joda-Time库提供了一组很好的对象,用于处理多个时区中的日期/时间。 http://joda-time.sourceforge.net/

例如:

    String date = "9/13/2012";
    String time = "5:48pm";

    String[] dateParts = date.split("/");
    Integer month = Integer.parseInt(dateParts[0]);
    Integer day = Integer.parseInt(dateParts[1]);
    Integer year = Integer.parseInt(dateParts[2]);

    String[] timeParts = time.split(":");
    Integer hour = Integer.parseInt(timeParts[0]);
    Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));

    DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
    dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));

答案 2 :(得分:1)

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*

另外,下面引用的是来自 home page of Joda-Time 的通知:

<块引用>

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,取代了该项目。

使用 java.time(现代日期时间 API)的解决方案:

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String date = "9/13/2012";
        String time = "5:48pm";

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
        LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);

        OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
        OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));

        System.out.println(odtTarget);

        // In a custom format
        System.out.println(odtTarget.format(dtf));
    }
}

输出:

2012-09-14T01:48+08:00
9/14/2012 1:48am

ONLINE DEMO

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project