如何在 groovy 脚本中将 UTC 时区转换为 CET 时区

How to convert UTC timezone to CET timezone in groovy script

UTC 格式的输入日期示例:'2021-08-31T22:00:00Z' CET输出日期格式:'DD-MM-YYYY'

tl;博士

Instant
        .parse( "2021-08-31T22:00:00Z" )                      // Returns a `Instant` object, a moment as seen in UTC.
        .atZone(                                              // Adjust from UTC to a specific time zone.
                ZoneId.of( "Europe/Stockholm" )
        )                                                     // Returns a `ZonedDateTime` object.
        .format(                                              // Generate text representing the value of our `ZonedDateTime` object. 
                DateTimeFormatter.ofPattern( "dd-MM-uuuu" )   // Or consider using `DateTimeFormatter.ofLocalizedDate` for localization.
        )                                                     // Returns a `String` object.

我们看到日期从 31 号翻转到 1 号。

01-09-2021

详情

在Java语法中...(我不知道Groovy)

将您的字符串输入转换为 Instant,因为两者都代表 UTC 中的一个时刻,偏移量为零小时-分钟-秒。

Instant instant = Instant.parse( "2021-08-31T22:00:00Z" ) ;

定义您要调整到的时区。 CETCSTIST等2-4个字母的伪时区实际上并不是时区。 real time zone 的命名格式为 Continent/Region.

ZoneId z = ZoneId.of( "Europe/Berlin" ) ;

通过将 ZoneId 应用到 Instant 来从 UTC 调整到时区以获得 ZonedDateTime

ZonedDateTime zdt = instant.atZone( z ) ;

只提取日期。

LocalDate ld = zdt.toLocalDate() ;

使用 DateTimeFormatter.ofPattern 生成文本。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;

示例代码。

Instant instant = Instant.parse( "2021-08-31T22:00:00Z" );
ZoneId z = ZoneId.of( "Europe/Stockholm" );
ZonedDateTime zdt = instant.atZone( z );
LocalDate ld = zdt.toLocalDate();
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
String output = ld.format( f );

看到这个 code run live at IdeOne.com

01-09-2021

技术上我们可以跳过 .toLocalDate

与 Basil 相同,但使用 CET 查询:

import java.time.*

String input = '2021-08-31T22:00:00Z'

String output = ZonedDateTime.parse(input)
    .withZoneSameInstant(ZoneId.of("Europe/Paris"))
    .format("dd-MM-yyyy")

可以

    .withZoneSameInstant(ZoneId.of("CET")) 

但正如 Basil 所说,不推荐使用这些缩写形式