[英]How to Convert a Date time value with UTC offset into GMT in java 7
我的日期时间值为2016-12-21T07:48:36,偏移量为UTC + 14。 如何将日期时间转换为等效的标准GMT时间。
我尝试使用sampleDateFormat.parse()
,我无法获得UTC偏移量的TimeZone对象。
sampleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC+14:00"))
请帮我在Java 7中将UTC日期时间转换为标准GMT时间。
我假设您将原始日期作为字符串。 请执行下列操作:
SimpleDateFormat
并将时区设置为“GMT + 14” Date
对象 SimpleDateFormat
的时区设置为“UTC”(或使用不同的SimpleDateFormat
实例) 例:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class ConvertToUTC {
public static void main(String[] args) throws Exception {
String dateval = "2016-12-21T07:48:36";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT+14"));
Date date = df.parse(dateval);
System.out.println(df.format(date)); // GMT+14
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(date)); // UTC
}
}
使用“GMT + 14:00”而不是“UTC + 14:00”
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("GMT+14:00"));
final Date d = f.parse("2016-12-21T07:48:36");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(d)); // -> 2016-12-20T05:48:36
LocalDateTime.parse( "2016-12-21T07:48:36" ) // Parse as a `LocalDateTime` given the lack of an offset or zone. *Not* an actual moment, only a rough approximation of potential moments along a range of about 26-27 hours.
.atOffset( ZoneOffset.ofHours( 14 ) ) // Assign an offset-from-UTC as context, giving meaning to determine an actual point on the timeline.
.toInstant() // Renders `Instant` object in UTC.
现代方法是使用Java 8及更高版本内置的java.time类。 许多功能都在ThreeTen-Backport项目中反向移植到Java 6和7。
ZoneOffset offset = ZoneOffset.ofHours( 14 ); // fourteen hours ahead of UTC.
将字符串解析为LocalDateTime
因为它缺少有关偏移量或区域的任何信息。 您的输入采用标准ISO 8601格式,因此无需指定格式设置模式。
LocalDateTime ldt = LocalDateTime.parse( "2016-12-21T07:48:36" );
将偏移量应用于本地日期时间以获取OffsetDateTime
对象。
OffsetDateTime odt = ldt.atOffset( offset );
从中,提取始终为UTC的Instant
。
Instant instant = odt.toInstant();
instant.toString():2016-12-20T17:48:36Z
在UTC中 ,值是不同的日期,即20日而不是21日。
查看IdeOne.com上的实时代码 。
java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧遗留日期时间类,如java.util.Date
, Calendar
和SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参阅Oracle教程 。 并搜索Stack Overflow以获取许多示例和解释。 规范是JSR 310 。
使用符合JDBC 4.2或更高版本的JDBC驱动程序 ,您可以直接与数据库交换java.time对象。 不需要字符串也不需要java.sql。*类。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。 该项目是未来可能添加到java.time的试验场。 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.