如何获取带有给定时区的给定时间和日期的Java中的UTC值?
例如,我当前的时区是Asia/Kolkata
,现在如何获得1.00 am on 21/07/2018
这样的UTC值?
答案 0 :(得分:2)
获取UTC的准确时间。
Instant.now() // Current time in UTC.
用于获取任何所需TimeZone中的当前时间。
ZonedDateTime.now( ZoneId.systemDefault() ) // Current time in your ZoneId.
加尔各答示例:
ZoneId zoneKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
要调整回UTC,请从Instant
中提取一个ZonedDateTime
。
Instant instant = zoneDTKolkata.toInstant() ;
您可以从UTC调整为时区。
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
答案 1 :(得分:0)
使用Java 8时间API代替较旧的API(即rajadilipkolli提出的Date和SimpleDateFormat解决方案)
// System time (ie, your operating system time zone)
LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, minute, second);
// Time in Asia/Kolkata
ZonedDateTime kolkata = ldt.atZone(ZoneId.of("Asia/Kolkata"));
// Time in UTC
OffsetDateTime utc = ldt.atOffset(ZoneOffset.UTC);
答案 2 :(得分:0)
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h.mm a 'on' dd/MM/uuuu")
.toFormatter(Locale.ENGLISH);
ZoneId zone = ZoneId.of("Asia/Kolkata");
String localDateTimeString = "1.00 am on 21/07/2018";
Instant i = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant();
System.out.println("UTC value is: " + i);
此打印:
UTC值是:2018-07-20T19:30:00Z
我不确定您是否需要将给出的确切字符串1.00 am on 21/07/2018
解析为日期时间对象,但是如果我已经演示了如何。挑战在于am
小写。为了指定不区分大小写的解析,我需要经过DateTimeFormatterBuilder
。
如您所见,代码将转换为Instant
,这是一种现代的表示Java时间点的方法。 Instant.toString
始终以UTC打印时间。最后的Z
表示UTC。如果您希望使用UTC更明确的日期时间,则可以使用
OffsetDateTime odt = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant()
.atOffset(ZoneOffset.UTC);
System.out.println("UTC value is: " + odt);
输出是相似的,如果OffsetDateTime
为0(零),则省略秒数:
UTC值是:2018-07-20T19:30Z
链接: Oracle tutorial: Date Time解释了如何使用现代Java日期和时间API java.time
。