将 UTC 转换为当前区域设置时间

发布于 2024-11-08 07:06:00 字数 377 浏览 6 评论 0原文

我正在从 Web 服务下载一些 JSON 数据。在此 JSON 中,我有一些日期/时间值。一切都以 UTC 时间为准。 如何解析此日期字符串,以便结果 Date 对象位于当前区域设置中?

例如:服务器返回“2011-05-18 16:35:01”,我的设备现在应该显示“2011-05-18 18:35:01”(GMT +2)

我当前的代码:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

I am downloading some JSON data from a webservice. In this JSON I've got some Date/Time values. Everything in UTC.
How can I parse this date string so the result Date object is in the current locale?

For example: the Server returned "2011-05-18 16:35:01" and my device should now display "2011-05-18 18:35:01" (GMT +2)

My current code:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

残月升风 2024-11-15 07:06:00

它有一个设置时区的方法:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

全部完成!

It has a set timezone method:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

all done!

剪不断理还乱 2024-11-15 07:06:00

所以你想告知 SimpleDateFormat UTC 时区:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

要显示:

simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(myDate);

So you want to inform SimpleDateFormat of UTC time zone:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

To display:

simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(myDate);
林空鹿饮溪 2024-11-15 07:06:00
public static String toLocalDateString(String utcTimeStamp) {
    Date utcDate = new Date(utcTimeStamp);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    df.setTimeZone(TimeZone.getTimeZone("PST"));
    return df.format(utcDate);
}

干杯!

public static String toLocalDateString(String utcTimeStamp) {
    Date utcDate = new Date(utcTimeStamp);
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    df.setTimeZone(TimeZone.getTimeZone("PST"));
    return df.format(utcDate);
}

Cheers!

⒈起吃苦の倖褔 2024-11-15 07:06:00

java.time

我想贡献现代答案。大多数其他答案都是正确的,并且在 2011 年都是很好的答案。如今,SimpleDateFormat 早已过时,而且它总是带来一些惊喜。今天我们有了更好的:java.time 也称为 JSR-310,现代 Java 日期和时间 API。这个答案适用于任何接受外部依赖项(直到 java.time 出现在您的 Android 设备上)或已经在使用 Java 8 或更高版本的人。

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String dateTimeFromServer = "2011-05-18 16:35:01";
    String localTimeToDisplay = LocalDateTime.parse(dateTimeFromServer, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("Europe/Zurich"))
            .format(formatter);

此代码片段的结果是所要求的:

2011-05-18 18:35:01

如果可以的话请给出明确的时区

我已经给出了欧洲/苏黎世的明确时区。请替换您所需的当地时区。要依赖设备的时区设置,请使用 ZoneId.systemDefault()。但是,请注意,这是脆弱的,因为它从 JVM 获取时区设置,并且该设置可能会被程序的其他部分或同一 JVM 中运行的其他程序更改。

在 Android 上使用 java.time

我向您保证了外部依赖项。要在 Android 上使用上述内容,您需要 ThreeTenABP、ThreeTen Backport 的 Android 版本、JSR-310 到 Java 6 和 7 的向后移植。 这个问题:如何在 Android 项目中使用 ThreeTenABP

java.time

I should like to contribute the modern answer. Most of the other answers are correct and were fine answers in 2011. Today SimpleDateFormat is long outdated, and it always came with some surprises. And today we have so much better: java.time also known as JSR-310, the modern Java date and time API. This answer is for anyone who either accepts an external dependency (just until java.time comes to your Android device) or is already using Java 8 or later.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String dateTimeFromServer = "2011-05-18 16:35:01";
    String localTimeToDisplay = LocalDateTime.parse(dateTimeFromServer, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("Europe/Zurich"))
            .format(formatter);

The result of this code snippet is what was asked for:

2011-05-18 18:35:01

Give explicit time zone if you can

I have given an explicit time zone of Europe/Zurich. Please substitute your desired local time zone. To rely on your device’s time zone setting, use ZoneId.systemDefault(). However, be aware that this is fragile because it takes the time zone setting from the JVM, and that setting could be changed under our feet by other parts of your program or other programs running in the same JVM.

Using java.time on Android

I promised you an external dependency. To use the above on Android you need the ThreeTenABP, the Android edition of ThreeTen Backport, the backport of JSR-310 to Java 6 and 7. How to go about it is nicely and thoroughly explained in this question: How to use ThreeTenABP in Android Project.

陌若浮生 2024-11-15 07:06:00

你的字符串 myUTC = "2016-02-03T06:41:33.000Z"

SimpleDateFormat existingUTCFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat requiredFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try{
Date getDate = existingFormat.parse(myUTC);
String mydate = requiredFormat.format(getDate)
}
catch(ParseException){
}

Your String myUTC = "2016-02-03T06:41:33.000Z"

SimpleDateFormat existingUTCFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat requiredFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try{
Date getDate = existingFormat.parse(myUTC);
String mydate = requiredFormat.format(getDate)
}
catch(ParseException){
}
一片旧的回忆 2024-11-15 07:06:00

Date 对象始终是自 UTC 纪元 0 以来的毫秒数的包装器。它从不代表当地时间。

这意味着您需要创建第二个 SimpleDateFormatter 来创建本地时间的显示字符串。

编辑:@Op。请注意,Android 上日期/时间格式化的首选类是 java.text.DateFormat

A Date object is always a wrapper around milliseconds since epoch 0 in UTC. It does never represent local time.

That means that you need to create a second SimpleDateFormatter that creates a display string that is in local time.

Edit: @Op. Note that the preffered class for date/time-formatting on Android is java.text.DateFormat

山人契 2024-11-15 07:06:00

如果您有一个时间戳(长)作为输入(对于 UTC 时间),因为这是在 Android 上,您可以执行以下操作:

fun DateFormat.formatUtcEpochSecond(epochSecond: Long): String = format(CalendarEx.getFromEpochSecond(epochSecond).time)

fun DateFormat.formatUtcEpochMs(epochMilli: Long): String = format(CalendarEx.getFromEpochMilli(epochMilli).time)

CalendarEx.kt

object CalendarEx {

    @JvmStatic
    fun getFromEpochMilli(epochMilli: Long): Calendar {
        val cal = Calendar.getInstance()
        cal.timeInMillis = epochMilli
        return cal
    }

    @JvmStatic
    fun getFromEpochSecond(epochSecond: Long): Calendar {
        val cal = Calendar.getInstance()
        cal.timeInMillis = epochSecond * 1000L
        return cal
    }
}

DateHelper.kt

/**
 * gets the default date formatter of the device
 */
@JvmStatic
fun getFormatDateUsingDeviceSettings(context: Context): java.text.DateFormat {
    return DateFormat.getDateFormat(context) ?: SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
}

/**
 * gets the default time formatter of the device
 */
@JvmStatic
fun getFormatTimeUsingDeviceSettings(context: Context): java.text.DateFormat {
    return DateFormat.getTimeFormat(context) ?: SimpleDateFormat("HH:mm", Locale.getDefault())
}

用法示例:

    val dateFormat = DateHelper.getFormatDateUsingDeviceSettings(this)
    val timeFormat = DateHelper.getFormatTimeUsingDeviceSettings(this)
    val timeStampSecondsInUtc = 1516797000L
    val localDateTime = Instant.ofEpochSecond(timeStampSecondsInUtc).atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0))).toLocalDateTime()
    Log.d("AppLog", "input time in UTC:" + localDateTime)
    Log.d("AppLog", "formatted date and time in current config:${dateFormat.formatUtcEpochSecond(timeStampSecondsInUtc)} ${timeFormat.formatUtcEpochSecond(timeStampSecondsInUtc)}")

If you had a timestamp (Long) as input instead (for the UTC time), since this is on Android, you can do something as such:

fun DateFormat.formatUtcEpochSecond(epochSecond: Long): String = format(CalendarEx.getFromEpochSecond(epochSecond).time)

fun DateFormat.formatUtcEpochMs(epochMilli: Long): String = format(CalendarEx.getFromEpochMilli(epochMilli).time)

CalendarEx.kt

object CalendarEx {

    @JvmStatic
    fun getFromEpochMilli(epochMilli: Long): Calendar {
        val cal = Calendar.getInstance()
        cal.timeInMillis = epochMilli
        return cal
    }

    @JvmStatic
    fun getFromEpochSecond(epochSecond: Long): Calendar {
        val cal = Calendar.getInstance()
        cal.timeInMillis = epochSecond * 1000L
        return cal
    }
}

DateHelper.kt

/**
 * gets the default date formatter of the device
 */
@JvmStatic
fun getFormatDateUsingDeviceSettings(context: Context): java.text.DateFormat {
    return DateFormat.getDateFormat(context) ?: SimpleDateFormat("yyyy/MM/dd", Locale.getDefault())
}

/**
 * gets the default time formatter of the device
 */
@JvmStatic
fun getFormatTimeUsingDeviceSettings(context: Context): java.text.DateFormat {
    return DateFormat.getTimeFormat(context) ?: SimpleDateFormat("HH:mm", Locale.getDefault())
}

Example usage:

    val dateFormat = DateHelper.getFormatDateUsingDeviceSettings(this)
    val timeFormat = DateHelper.getFormatTimeUsingDeviceSettings(this)
    val timeStampSecondsInUtc = 1516797000L
    val localDateTime = Instant.ofEpochSecond(timeStampSecondsInUtc).atZone(ZoneId.ofOffset("UTC", ZoneOffset.ofHours(0))).toLocalDateTime()
    Log.d("AppLog", "input time in UTC:" + localDateTime)
    Log.d("AppLog", "formatted date and time in current config:${dateFormat.formatUtcEpochSecond(timeStampSecondsInUtc)} ${timeFormat.formatUtcEpochSecond(timeStampSecondsInUtc)}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文