2

次のようなタイムスタンプ文字列があります。

String build_time=2017-11-20T21:27:03Z

結果が次のようになるように、PSTタイムゾーンに従ってミリ秒単位のエポック時間に変換したい:

long build_time_ms=1511299623000

これどうやってするの?

4

1 に答える 1

9

java.time.*これは、Java のパッケージを使用して実現できます。以下は、docker を介して groovy を実行した場合の作業スクリプトと出力です。defただし、Jenkins 内でこれを試したことはありません。パイプラインのシリアル化の問題を回避するために、スクリプトに適切なステートメントを追加する必要がある場合があります。

脚本

import java.time.*

// build time as string
build_time='2017-11-20T21:27:03Z'

// parse and get epoch
time=Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", build_time)

// get epoch milis
epoch_milis = time.getTime()

// create UTC local time
local_dt = LocalDateTime.ofInstant(Instant.ofEpochMilli(epoch_milis), ZoneId.of('UTC'));

// created zoned time out of UTC time
zoned_dt = local_dt.atZone(ZoneId.of('America/Los_Angeles'))

// get offset in milis
offset_ms = zoned_dt.getOffset().getTotalSeconds() * 1000

// add to UTC epoc
local_timestamp = epoch_milis + offset_ms

println "Time is ${local_timestamp}"

groovy REPL で実行されるスクリプト出力

$ docker run --rm -it groovy
Nov 21, 2017 3:37:26 AM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
Groovy Shell (2.4.12, JVM: 1.8.0_141)
Type ':help' or ':h' for help.
----------------------------------------------------------------------------------------------------------------------------------------------------------------
groovy:000> import java.time.*
===> java.time.*
groovy:000> 
groovy:000> // build time as string
===> true
groovy:000> build_time='2017-11-20T21:27:03Z'
===> 2017-11-20T21:27:03Z
groovy:000> 
groovy:000> // parse and get epoch
===> true
groovy:000> time=Date.parse("yyyy-MM-dd'T'HH:mm:ss'Z'", build_time)
===> Mon Nov 20 21:27:03 UTC 2017
groovy:000> 
groovy:000> // get epoch milis
===> true
groovy:000> epoch_milis = time.getTime()
===> 1511213223000
groovy:000> 
groovy:000> // create UTC local time
===> true
groovy:000> local_dt = LocalDateTime.ofInstant(Instant.ofEpochMilli(epoch_milis), ZoneId.of('UTC'));
===> 2017-11-20T21:27:03
groovy:000> 
groovy:000> // created zoned time out of UTC time
===> true
groovy:000> zoned_dt = local_dt.atZone(ZoneId.of('America/Los_Angeles'))
===> 2017-11-20T21:27:03-08:00[America/Los_Angeles]
groovy:000> 
groovy:000> // get offset in milis
===> true
groovy:000> offset_ms = zoned_dt.getOffset().getTotalSeconds() * 1000
===> -28800000
groovy:000> 
groovy:000> // add to UTC epoc
===> true
groovy:000> local_timestamp = epoch_milis + offset_ms
===> 1511184423000
groovy:000> 
groovy:000> println "Time is ${local_timestamp}"
Time is 1511184423000

また、あなたの例では、1511299623000 ミリ秒の結果を示しています。これは、タイムスタンプより 24 時間進んでいるように見えます。JavaScript コンソールを見て、例からの入力を使用します。

new Date('2017-11-20T21:27:03Z')
>> Tue Nov 21 2017 08:27:03 GMT+1100 (AEDT)

new Date(1511299623000)
>> Wed Nov 22 2017 08:27:03 GMT+1100 (AEDT)
于 2017-11-21T03:37:04.583 に答える