LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

PowerShellで短めのタイムスタンプ文字列を作る

Last updated at Posted at 2016-12-18

用途・目的

  • ファイルの名前などに付ける、タイムスタンプ文字列を生成したい。
    • 「scrshot_*****.png」 など。
  • さらに、文字列をなるべく短くしたい。
    • (Get-Date).ToString("yyyyMMdd_HHmmss") ですら長すぎる場合に。

方針

  • 人間が直接読めなくてもよいものとする。
    • (Get-Date).Ticks を使う。
      • 16進数に変換すれば、さらに文字列を圧縮できそう。

コード(シンプル版)

[Convert]::ToString((Get-Date).Ticks, 16)
実行結果
8d426be3174c09d

元の時間を得るには

filter Get-DateFromHexTicksString { [Convert]::ToInt64($_, 16) | Get-Date }
"8d426be3174c09d" | Get-DateFromHexTicksString
  • あるいは

    filter Get-DateFromHexTicksInt { [Convert]::ToInt64($_) | Get-Date }
    0x8d426be3174c09d | Get-DateFromHexTicksInt
    
実行結果
2016年12月17日 20:49:28

もっと短くしたい

先頭の 2 桁を削る

  • 次にここの桁が上がる(8e0000000000000 になる)のは 2027年7月13日 22:31:48
  • 当面は 8d... を想定していて大丈夫そう。

末尾の 5 桁を削る

  • 1 秒の Ticks 値を16進数に変換すると...

    [Convert]::ToString((Get-Date("0001/01/01 00:00:01")).Ticks, 16)
    
    • この結果は 989680
      • 末尾の 6 桁目が 1 秒単位の解像度を持っていることが分かる。
      • ゆえに、1 秒未満の精度が不要な場合は、末尾の 5 桁目以降を削ることができそう。

コード(8桁の短縮版)

[Convert]::ToString((Get-Date).Ticks, 16).SubString(2, 8)
実行結果
426be317

「8桁の短縮版」から元の時間を得るには

filter Get-DateFromShortenedHexTicksString { [Convert]::ToInt64("8d" + $_ + "00000", 16) | Get-Date }
"426be317" | Get-DateFromShortenedHexTicksString
実行結果
2016年12月17日 20:49:28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up