日历时间 = Calendar.getInstance(TimeZone.getTimeZone(Utils.merchantTimeZone));
TimeZone 已替换为 ZoneId。
ZoneId z = ZoneId.of( "America/Edmonton" ) ; // Or `Africa/Tunis`, `Europe/Paris`, etc.
Calendar 类已替换为 ZonedDateTime。拨打now捕捉当前时刻。
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z");
最好自动本地化。要进行本地化,请指定:
代码:
FormatStyle style = FormatStyle.LONG ;
Locale locale = new Locale( "en" , "IN" ) ; // English in India.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( style ).withLocale( locale ) ;
String output = zdt.format( f ) ;
2019 年 7 月 26 日晚上 7:28:36 GMT-06:00
如果您希望对格式模式进行硬编码,请在 StackOverflow 中搜索 DateTimeFormatter.ofPattern。这已经讲过很多次了。
rawTime = time.get(Calendar.HOUR) +""+ time.get(Calendar.MINUTE);
如果您只想要没有日期和时区的时间部分,请提取LocalTime。
LocalTime lt = zdt.toLocalTime() ;
如果您只需要小时和分钟而不需要秒和小数秒,truncate。
LocalTime lt = zdt.toLocalTime().truncatedTo( ChronoUnit.MINUTES ) ;
我想把它转换成 UTC 时区
您的这部分问题不清楚。如果您想从分区时刻调整以在 UTC 中看到同一时刻,只需转换为 OffsetDateTime 对象并使用 ZoneOffset.UTC 常量调整为 UTC。
OffsetDateTime odt = zdt.toOffsetDateTime() ;
OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC ) ;
带有时区的ZonedDateTime 和带有UTC 偏移量的OffsetDateTime 之间有什么区别?偏移量只是几个小时-分钟-秒,仅此而已。时区更多。时区是特定地区的人们使用的偏移量的过去、现在和未来变化的历史。
当我将 0830(亚洲/加尔各答)传递给 rawTime 时,我得到了 1400,这不是正确的 UTC 时间
显然您想指定日期的时间。
首先获取今天的日期,例如。
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
LocalDate ld = LocalDate.now( z ) ; // Current date as seen in India right now.
指定您的时间。
LocalTime lt = LocalTime.of( 8 , 30 ) ;
组合所有三个部分以获得ZonedDateTime。如果该时间在该区域的该日期无效,ZonedDateTime 将进行调整。
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
zdt.toString(): 2019-07-27T08:30+05:30[亚洲/加尔各答]
要在 UTC 中查看同一时刻,请提取 Instant。根据定义,Instant 类始终采用 UTC。
Instant instant = zdt.toInstant() ;
instant.toString(): 2019-07-27T03:00:00Z
注意一天中的时间。在这一天,印度比世界标准时间早五个半小时。因此,UTC 时间凌晨 3 点的时间减少了 5.5 小时。
是否可以将 23:00(亚洲/加尔各答)转换为 UTC 小时
是的,类似于上面的代码。在这里,我们也可以调用ZonedDateTime::with。
ZonedDateTime
.now(
ZoneId.of( "Asia/Kolkata" )
)
.with(
LocalTime.of( 23 , 0 )
)
.toInstant()
.toString()
2019-07-27T17:30:00Z
同样,在这一天,印度比 UTC 早五个半小时。因此,从晚上 11 点开始往回拨 5.5 小时表示下午 5:30。
此处看到的类内置于 Java 8 及更高版本以及 Android 26 及更高版本。