当我创建一个新的Date对象时,它被初始化为当前时间,但在本地时区。如何获得当前的GMT日期和时间?
当前回答
转换UTC当前日期时间:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone
DateTime currDateTime = new DateTime(); //Current DateTime
long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);
String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter
currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC
其他回答
使用java。时间包和包括以下代码-
ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC );
or
LocalDateTime now2 = LocalDateTime。now (ZoneOffset。UTC);
这取决于您的应用程序需要。
你可以使用:
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
然后,使用aGMTCalendar对象执行的所有操作都将使用GMT时区完成,并且不会应用夏令时或固定偏移量。我认为之前的帖子是正确的,Date()对象总是返回GMT,直到你对Date对象做一些事情,它才被转换为本地时区。
转换UTC当前日期时间:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone
DateTime currDateTime = new DateTime(); //Current DateTime
long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);
String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter
currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC
你可以使用的简单函数:
编辑:这个版本使用现代java。时间类。
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss z");
public static String getUtcDateTime() {
return ZonedDateTime.now(ZoneId.of("Etc/UTC")).format(FORMATTER);
}
方法返回值:
26-03-2022 17:38:55 UTC
最初的功能:
public String getUTC_DateTime() {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));//gmt
return dateTimeFormat.format(new Date());
}
以上函数返回:
26-03-2022 08:07:21 UTC
以下是乔恩·斯基特的回答中似乎不正确的地方。他说:
date始终使用UTC。你凭什么认为它是本地的 时间吗?我怀疑问题在于您通过 使用本地时区的Calendar实例,或者可能使用 Date.toString(),它也使用本地时区。
然而,代码:
System.out.println(new java.util.Date().getHours() + " hours");
给出的是本地时间,而不是GMT (UTC)时间,完全没有使用Calendar和SimpleDateFormat。
这就是为什么看起来有些事情是不正确的。
把这些回答放在一起,代码如下:
System.out.println(Calendar.getInstance(TimeZone.getTimeZone("GMT"))
.get(Calendar.HOUR_OF_DAY) + " Hours");
显示GMT时间而不是本地时间——请注意,getTime.getHours()缺失,因为这将创建一个Date()对象,该对象理论上以GMT存储日期,但返回本地时区的小时。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 解析日期字符串并更改格式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?