1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Windowsバッチ オフセット付き現在時刻取得用ワンライナー

Posted at

概要

他のプログラムの引数にオフセット付き時間を渡すための設定値で、デフォルトを現在時刻にしたかった。
標準だとそんなAPIはなさそうなので、JScriptを呼び出してDate#getTimezoneOffset()を利用することに。

コード

for /f "usebackq delims=" %%0 in (`mshta "javascript:window.onunload=function(){function f(d){function c(V,S){return ('00'+V).slice(-1*S)}var o=d.getTimezoneOffset();return c(d.getFullYear(),4)+'-'+c(d.getMonth()+1,2)+'-'+c(d.getDate(),2)+' '+c(d.getHours(),2)+':'+c(d.getMinutes(),2)+':'+c(d.getSeconds(),2)+'.'+c(d.getMilliseconds(),3)+' '+(o<0?'+':'-')+c(Math.abs(o)/60,2)+':'+c(Math.abs(o)%% 60,2)}new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(f(new Date()))};close()"`) do @set "OFFSET_DATETIME=%%0"

ポイント

  • mshtaでJScriptを起動してワンライナー。
  • new Date()で生成した現在時刻から各パラメータを切り出して標準出力に吐き出す。
    • formatくらい標準でほすぃ。
  • mshtaは512文字?までしかスクリプトを受け付けてくれないので、収まる程度に手動でminify。もっと見やすくもできるかもしれないけど、とりあえず目的に適うのでこれで。
  • getTimezoneOffset()はオフセットを分単位で返す上に符号が直感と逆なので注意。
    • +09:00は-540。
  • あとはバッチのforで環境変数に展開。
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?