1
1

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 1 year has passed since last update.

◇Windowsのバッチファイルで日時を好みのフォーマットで作成

Last updated at Posted at 2022-07-23

◇日時を好みのフォーマットで作成

バッチファイルの中で日付や曜日、時刻を表示したい時がありますが自由なフォーマットにするのは案外難しいです。
次の方法なら見た目にもシンプルで自由度が高いのでお勧めです。
フォーマットの書式は

内容 変数
西暦 %%1
%%2
%%3
曜日 %%4
%%5
%%6
%%7
ミリ秒 %%8

上記を参考に

表記 記述式
YYYY/MM/DD(Week) HH:MM:SS.MS %%1/%%2/%%3(%%4) %%5:%%6:%%7.%%8
MM/DD HH:MM %%2/%%3 %%5:%%6

のように区切り文字を自由に指定して必要ないものは省けます。
次にサンプルを掲載します。

日時を好みのフォーマットで作成のサンプル

YMDHMS.bat
@echo off


:: 遅延展開宣言 バグの原因になる場合があります;
setlocal enabledelayedexpansion


:: 日時を好みのフォーマットで作成;
set WeekChar="Sun,Mon,Tue,Wed,Thu,Fri,Sat"
powershell.exe "exit (Get-Date).DayOfWeek"
set /a WEEKDAY=%ERRORLEVEL% + 1
for /f "tokens=%WEEKDAY% delims=," %%w in (%WeekChar%) do set WEEK=%%w
for /f "tokens=1-8 delims=/:. " %%1 in ("%date% %WEEK% %time: =0%") do set YMDHMS=%%1/%%2/%%3/(%%4) %%5:%%6:%%7.%%8
echo 今の日時は%YMDHMS%です。


:: 終了処理(エクスプローラーから起動されていた場合はPauseする);
:EndProcess
echo %cmdcmdline%|find /i "%~f0">NUL
if %ERRORLEVEL% equ 0 Pause
goto :end

Powershellを使いたくない場合はツェラーの公式が使えます。

Powershell.DayOfWeek
powershell.exe "exit (Get-Date).DayOfWeek"

の代わりに

Zeller's congruence
set /a YY=%DATE:~0,4%
set /a MM=%DATE:~5,2%
set /a DD=%DATE:~8,2%
if %MM% leq 2 (set /a YY=%YY% - 1 && set /a MM=%MM% + 12)
set /a WEEKDAY=((%YY% + %YY% / 4 - %YY% / 100 + %YY% / 400 + (13 * %MM% + 8) / 5 + %DD%) %% 7) + 1

に変更します。

環境に依存しにくい日時の取得

コメントの指摘をもとに考えてみました。
作成したファイルから日付と時刻を取得していますので秒は取得できません。

type NUL>$$$
for %%0 in ($$$) do for /f "tokens=1-5 delims=/: " %%1 in ("%%~t0") do set YMDHM=%%1/%%2/%%3 %%4:%%5
del $$$
echo %YMDHM%

おわりに

他にも「⧉Windowsのバッチファイルのテクニックをご紹介します」にてご紹介させて頂いております。
お時間ありましたら覗いてみてください
お粗末様でした。

1
1
3

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?