以 UTC 格式获取设备时间,无论时区如何

问题描述 投票:0回答:3

我如何获取设备的当地时间并将其转换为我所在国家/地区的全球 UTC 格式?

java android datetime timezone utc
3个回答
5
投票

根本不要获取本地时间 - 只需获取 UTC 值即可,例如

long millis = System.currentTimeMillis();

或者:

Date date = new Date();

如果您需要将其格式化为字符串,请使用

SimpleDateFormat
但请记住适当设置时区。例如:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                                               Locale.US);
format.setTimeZone(TimeZone.getTimeZone("Etc/Utc"));
String text = format.format(new Date());

(不清楚“我的国家/地区的全球 UTC 格式”是什么意思 - UTC 只是全球的,而且它不是格式,它是一个时区。)


1
投票

不确定你想做什么,但如果你想要正常格式的日期和时间,你可以这样做:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Calendar cal = Calendar.getInstance();
String dateAndTime = dateFormat.format(cal.getTime());

String dateAndTime 将类似于

2012/01/01 11:13
,根据设备设置的日期和时间,因此它显示与设备时钟相同的时间。 您可以通过将
"yyyy/MM/dd HH:mm"
更改为您喜欢的任何内容来稍微尝试一下格式。

希望这有帮助!

更新: 要获取 UTC 时间,请这样做:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateAndTimeUTC = dateFormat.format(new Date());

0
投票

现有答案是正确的,并且它们在 2012 年 11 月(提出问题时)提供了正确的方向。 2014 年 3 月,现代日期时间 API 作为 Java 8 标准库的一部分发布,它取代了容易出错的

java.util
日期时间 API 及其相应的解析/格式化类型
SimpleDateFormat
,以及从那时起,强烈建议切换到现代日期时间 API
java.time

使用
java.time
的解决方案:

您可以简单地使用

Instant#now
来获取独立于时区(即 UTC)的当前时刻。请注意,
java.time
API 基于 ISO 8601 标准

如果您需要特定时区的当前日期时间,可以使用

ZonedDateTime#now(ZoneId)
,您也可以将其格式化为所需的格式。

演示:

class Main {
    public static void main(String[] args) {
        // Current moment
        System.out.println(Instant.now());

        // Current date-time in a specific timezone e.g. America/New_York
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
        System.out.println(zdt);

        // Output in a custom format e.g. EEE MMM dd, uuuu 'at' hh:mm:ss a
        String formattedStr = zdt.format(DateTimeFormatter.ofPattern("EEE MMM dd, uuuu 'at' hh:mm:ss a", Locale.ENGLISH));
        System.out.println(formattedStr);
    }
}

在线演示

注意: 切勿将

DateTimeFormatter
用于自定义格式,以及不使用
SimpleDateFormat
而不使用
Locale

Trail:日期时间了解有关现代日期时间 API 的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.