バッチで日付や時間を取得できれば出来る事は多くなります。
例えば本日の日付と時間を組み合わせて、ログファイルやディレクトリを作成するなどです。
そうする事により日々の自動化しているバッチのログを取得できたりします。

初心者向けになるべく簡単な方法で日付と時間を取得する方法をお伝えします。
windowsのプロンプトで使用できるbatやpythonやphpを使用して、業務効率化やWebサイトを作成しております。javaやシェルスクリプトなど、様々なプログラミングを行った実績ありの筆者です。
バッチで日付や時間を取得する方法


バッチで日付や時間を取得する方法は、環境変数の「DATE」と「TIME」を使用するだけです。
@echo off
echo 日付は:%date%
echo 時間は:%time%
バッチで変数を展開する場合は、変数の前後に「%」をつけます。
「date」を展開すると日付になり、「time」は時間となります。


このバッチファイルを実行してみます。


日付は:2023/11/27
時間は:16:43:08.63
現在の日付と時間が取得できています。
実用編:バッチで日付と時間でログファイルを作成する。


では実際に現在の日付と時間を使用して、ログファイルを作成してみましょう!
@echo off
echo ログ内容 >> %date%%time%.log


日付と時間をファイル名にするとエラーが出る原因と対処法
実行してみるとログファイルが出来ていません。
バッチファイルの最後に「pause」を入れて、状態を見てみます。


ファイル名、ディレクトリ名、またはボリューム ラベルの構文が間違っています。
エラーの原因はwindowsでファイル名として使用できない文字があるからです。このままではファイルは作成できません。



現在の日付と時間を使用してログファイルなどを作成したいです。普通に取得したけど「/」や「:」や「.」が邪魔です。何とかならないですか?
日付と時間の出力を編集する
日付は:2023/11/27
時間は:16:43:08.63
日付は「/」が邪魔です。「/」を無に置き換えたいです。
簡単にできます。以下の様にバッチを変更してください。
%date:/=%
時間は「:」が邪魔で「.」も邪魔です。「.」以下はミリ秒なので不要です。
set time1=%time::=%
echo %time1:~0,6%
変数「time1」を作成して日付同様不要な「:」を無に置き換えして代入しています。
その変数の0番目から6文字取得しています。


この二つを使用してログファイルを出力してみます。
set time1=%time::=%
echo ログ内容 >> %date:/=%%time1:~0,6%.log
バッチファイルと同じディレクトリにログファイル「20231127171535.log」が出来たと思います。
バッチで文字列を結合するやり方は、そのまま文字列を並べるだけなので下のように簡単に変更できます。
set time1=%time::=%
echo ログ内容 >> %date:/=%-%time1:~0,6%.log
ログファイル「20231127-171715.log」が出来ています。
実用編:バッチで日付と時間でディレクトリを作成する。


では最後にディレクトリも作成してみます。
先程のログ出力の「echo ログ内容 >>」をディレクトリ作成する「mkdir」に変更するだけです。
mkdir %date:/=%-%time1:~0,6%
これで「20231127-172410」というディレクトリが作成されました!

