Bil*_*hah 6 java date java-8 zoneddatetime
我正在尝试将日期06-12-2015 02:10:10 PM从默认区域转换为UTC ZonedDateTime.
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
ZonedDateTime utc = ZonedDateTime.of(localDateTime, ZoneOffset.UTC);
Run Code Online (Sandbox Code Playgroud)
但utc返回2015-12-06T14:10:10Z而不是06-12-2015 09:10:10 AM
如何将日期从默认区域转换为UTC?这里给出的答案将当前时间转换为UTC.
Ell*_*sch 16
您可以使用ZonedDateTime.ofInstant(Instant, ZoneId)第二个参数所在的位置UTC(即时知道本地偏移).就像是,
String source = "06-12-2015 02:10:10 PM";
String pattern = "MM-dd-yyyy hh:mm:ss a";
DateFormat sdf = new SimpleDateFormat(pattern);
try {
Date date = sdf.parse(source);
ZonedDateTime zdt = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC"));
System.out.println(zdt.format(DateTimeFormatter.ofPattern(pattern)));
} catch (ParseException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我得到(对应我的本地区域偏移)
06-12-2015 06:10:10 PM
Run Code Online (Sandbox Code Playgroud)