2

I use the following to get the current date/time in a more readable format:

set day=%date:~4,2%
set mth=%date:~7,2%
set yr=%date:~10,4%
set hur=%time:~0,2%
set min=%time:~3,2%
set bdate=[%day%-%mth%-%yr%]-[%hur%-%min%]

This works well and outputs something like: [02-06-2020]-[22-59]

However, after midnight the time format changes from HH:MM:SS:MS to H:MM:SS:MS. That messes up the format because it includes the colon : in the time because of the characters are shifted over by one. That results in a not useful date/time information in the log file created after midnight.

Is there any way to get the time always in the format with two digits for the hour?

Mofi
  • 38,783
  • 14
  • 62
  • 115
Piriwn1
  • 31
  • 2
  • You could also apply what you want to from this in order to convert it to 24 hour time. `https://stackoverflow.com/a/60094011/12343998` – T3RR0R Feb 08 '20 at 09:15
  • you really should use a [method independent of localization and user settings](https://stackoverflow.com/questions/7727114/batch-command-date-and-time-in-file-name/18024049#18024049) to get a reliable date/time string. – Stephan Feb 08 '20 at 11:59

4 Answers4

2

The usage of the dynamic environment variables DATE and TIME with string substitutions as explained very detailed by my answer on the question What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean? is very fast, but has the disadvantage that the format of the date and the time string depends on region (country) configured for the account used on running the batch file.

The date can be without or with abbreviated weekday at beginning and without or with a comma appended after abbreviated weekday. The date string can be in the format year/month/day or month/day/year or day/month/year with / or . or - or   as separator. See also the Wikipedia article about date format by country.

The time can be in 12 or 24 hour format. The hour can be without or with a leading 0 on being less than 10.

It was not posted what is output on running echo %DATE% %TIME% before ten o'clock in the morning and at three o'clock in the afternoon to know the local date/time format.

It looks like it is possible to use the following code with : as separator in time string:

if "%TIME:~1,1%" == ":" (
    set "bdate=[%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%]-[0%TIME:~0,1%-%TIME:~2,2%]"
) else (
    set "bdate=[%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%]-[%TIME:~0,2%-%TIME:~3,2%]"
)

If the second character in time string is a colon, the condition is true and the first expression is used with 0 added left to single digit hour, otherwise the ELSE block is used with the two digit hour.

Another solution with separator in time string being either a colon or a dot or a space would be:

for /F "tokens=1,2 delims=:. " %%I in ("%TIME%") do set "Hour=0%%I" & set "Minute=%%J"
set "bdate=[%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%]-[%Hour:~-2%-%Minute%]"

The hour left to : or . or   is assigned to environment variable Hour with a leading zero. The minute right to : or . or   is assigned to variable Minute. The date/time string is built with taking only the last two digits of Hour to have the hour finally always with two digits in date/time string assigned to environment variable bdate.


Much better would be getting current date and time region (country) independent and reformat them to wanted format using string substitutions.

A region independent date/time string can be get using Windows Management Instrumentation Command line tool WMIC.

The command line

wmic OS GET LocalDateTime /VALUE

outputs UTF-16 Little Endian encoded for example:



LocalDateTime=20200208124514.468000+060


There are two empty lines, then the line with the current local date/time in format yyyyMMddHHmmss.microsecond±UTC offset in minutes and two more empty lines.

The data can be used with a batch code like this:

@echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "DateTime=%%I"
set "bdate=[%DateTime:~6,2%-%DateTime:~4,2%-%DateTime:~0,4%]-[%DateTime:~8,2%-%DateTime:~10,2%]"

Of interest is here only the date/time string between the equal sign and the decimal point which is the reason for using for /F options tokens=2 delims==. to get just 20200208124514 assigned to loop variable I of which value is assigned next to environment variable DateTime.

The environment variable DateTime is reformatted using string substitutions to get the date/time string in format [dd-MM-yyyy]-[HH-mm] resulting in environment variable bdate being defined with [08-02-2020]-[12-45].

It would be of course possible to use bdate everywhere instead of DateTime to use just one environment variable instead of two variables.

The advantage of using WMIC to get local date/time is its independence on Windows region settings and that it is working even on Windows XP. The disadvantage is that the command execution takes a quite long time (one to two seconds) in comparison to the usage of the DATE and TIME environment variables which are accessed in a few microseconds.

The command FOR has problems parsing UTF-16 LE encoded Unicode output correct. It interprets the byte sequence 0D 00 0A 00 (carriage return + line-feed) of the WMIC output wrong as 0D 0D 0A, i.e. as two carriage returns and one line-feed. This results in interpreting the last two empty lines at end of WMIC output as two lines with a single carriage return as string.

That is very often a problem because the result of set "EnvironmentVariable=%%I" is with %%I expanding to just carriage return the deletion of the environment variable already defined before with the correct value.

There are multiple solutions to work around this Unicode parsing error of command FOR. It is possible to append & goto Label to exit the loop with a jump to :Label below the FOR loop once the value is assigned to the environment variable to avoid running into this problem at all.

Another solution is using if not defined DateTime set "DateTime=%%I" with set "DateTime=" above the FOR command line to make sure the command SET is executed only once.

One more solution is the one used in this code. The name of the property and its value are output on same line because of using WMIC option /VALUE. The command FOR runs the command SET because of tokens=2 only when it could split up the current line into at least two substrings (tokens) using equal sign and dot as delimiters because of delims==.. But the wrong parsed empty lines of WMIC output is for FOR just a line containing only a carriage return and therefore has no second token. For that reason the wrongly parsed empty lines are also ignored here by the command FOR.

See How to correct variable overwriting misbehavior when parsing output? and cmd is somehow writing Chinese text as output for details on parsing problem of FOR on UTF-16 LE encoded output.


Another solution to get current date and time region independent is using ROBOCOPY which is available since Windows Vista and Windows Server 2003 in system directory of Windows, but is by default not available on Windows XP. robocopy.exe of Windows Server 2003 can be copied to %SystemRoot%\System32 of Windows XP to use this executable also on Windows XP, but it is not available by default on Windows XP.

ROBOCOPY is executed with invalid source directory string "C:\|" and valid destination directory string . (could be also something other valid) and argument /NJH to suppress the output of the header information.

robocopy "C:\|" . /NJH

This execution produces the error message:


2020/02/08 12:45:14 ERROR 123 (0x0000007B) Accessing Source Directory C:\|\
The filename, directory name, or volume label syntax is incorrect.

The format of current date/time at beginning of second line after the empty line is region independent.

This output can be processed with:

set "bdate="
for /F "tokens=1-5 delims=/: " %%I in ('%SystemRoot%\System32\robocopy.exe "%SystemDrive%\|" . /NJH') do if not defined bdate set "bdate=[%%K-%%J-%%I]-[%%L-%%M]"

FOR starts in this case one more command process in background with %ComSpec% /c and the command line between the two ' appended as additional arguments which results in Windows being installed into C:\Windows in the execution of:

C:\Windows\System32\cmd.exe /c C:\Windows\System32\robocopy.exe "C:\|" . /NJH

The first five slash or colon or space separated strings of the first non-empty line of the error message output to handle STDOUT of the background command process captured by FOR are assigned to:

  • I ... year
  • J ... month
  • K ... day
  • L ... hour
  • M ... minute

The five data strings are concatenated to the date/time string in the wanted format.

But FOR would run the command SET once again for the second error message line. For that reason the environment variable bdate is explicitly undefined before running FOR. The environment variable bdate is defined first with the date/time string and is next not modified anymore on FOR processing the second non-empty line because of the additional IF condition to avoid overwriting the date/time string of interest with an unwanted string.

The advantage of the ROBOCOPY solution in comparison to the WMIC solution is its much faster execution time.


For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • for /?
  • if /?
  • robocopy /?
  • set /?
  • wmic /?
  • wmic os /?
  • wmic os get /?
  • wmic os get localdatetime /?

PS: There are lots of other solutions to get current date/time in a specific format independent on country configured for the used account. All those alternative solutions can be found in the answers on:

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Mofi
  • 38,783
  • 14
  • 62
  • 115
2

The problem is that you're using the %DATE% and %TIME% variable values, which contain strings which are not consistent across locales, PC's, or users.

The best advice is to retrieve the information using an alternative method, for example:

@For /F "Tokens=1-5Delims=/: " %%G In (
    '""%__AppDir__%Robocopy.exe" \: . /NJH /L|"%__AppDir__%find.exe" " 123""'
)Do @Set "bdate=[%%I-%%H-%%G]-[%%J-%%K]"

The method involves generating an error message from the built-in utility. We do that by asking it to copy from a target directory named : in the root of the current drive, \. An error is returned because Windows does not allow directory names containing the character :. That error message, regardless of locale, PC, or user, always outputs a line starting with the date and time strings in a known format, yyyy/MM/dd hh:mm:ss.

Examples:

2020/02/08 01:25:04 ERROR 123 (0x0000007B) Accessing Source Directory C:\:\
The filename, directory name, or volume label syntax is incorrect.

2020/02/08 01:25:04 ОШИБКА 123 (0x0000007B) Доступ к исходной папке C:\:\
‘Ё*в*ЄбЁзҐбЄ*п ®иЁЎЄ* ў Ё¬Ґ*Ё д*©«*, Ё¬Ґ*Ё Ї*ЇЄЁ Ё«Ё ¬ҐвЄҐ ⮬*.

2020/02/08 01:25:04 ERREUR 123 (0x0000007B) Copie du fichier C:\:\
La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte.

2020/02/08 01:25:04 FEHLER 123 (0x0000007B) Zugriff auf Zielverzeichnis C:\:\
Die Syntax für den Dateinamen, Verzeichnisnamen oder die Datenträgerbezeichnungist falsch.

We run our Robocopy command inside a in order that we can capture the required strings according to their known line position, format, and separator characters. We also need to account for the fact that the output consists of more than one line. To select the line, I have used the built-in utility, and chosen to match only lines containing the string  123 as it cannot appear elsewhere in the output. Next I split the line up using the known separator characters as delimiters and choose how many delimiter separated token components to return. I choose a forward slash, /, which delimits the individual date components, a colon. :, which delimits the individual time components, and a space,  , which separates date and time from the rest of the line and each other. For your user case you only wanted five token components:

    ↓  ↓  ↓  ↓  ↓    delims
2020/02/08 01:25:04
↑    ↑  ↑  ↑  ↑
 1    2  3  4  5     tokens
 %G  %H %I %J %K

The final thing I do is to put each of the components together in the required order and format, saving it as a string value within a variable named bdate. You should be able to use that value elsewhere in the script, as %bdate%, or !bdate! if delayed expansion is enabled.

To get more information of how to use a , please open a Command Prompt window and enter for /?.

Compo
  • 30,301
  • 4
  • 20
  • 32
  • This works excellently, thank you very much and thank you for explaining how/why, im kinda learning as i go making batch files for work and so far ive just been fumbling forward so far. – Piriwn1 Feb 08 '20 at 19:19
0
set "day=%date:~4,2%"
set "mth=%date:~7,2%"
set "yr=%date:~10,4%"
set "_time=0%time%"
set "hur=%_time:~-11,2%"
set "min=%_time:~-8,2%"
set bdate=[%day%-%mth%-%yr%]-[%hur%-%min%]

You can pad time with a 0 and then do the substitution from the right side using negative numbers as the start position of the string. 1:00 would become 01-00 to match the pattern of HH-MM.

michael_heath
  • 5,042
  • 2
  • 9
  • 21
0
  • If using wmic.exe is an option, I would like to suggest this code to adjust your variable and output layout...
@echo off && setlocal enabledelayedexpansion 

for /f "tokens=2delims==." %%i in ('
%__APPDIR__%\wbem\wmic OS Get LocalDateTime /value^|%__APPDIR__%findstr [0-9]')do set "dt=%%~i"

set "day=!dt:~6,2!"
set "mth=!dt:~4,2!"
set "yr=!dt:~0,4!"
set "hur=!dt:~8,2!"
set "min=!dt:~10,2!"

echo/[!day!-!mth!-!yr!]-[!hur!-!min!]

endlocal && goto :EOF

  • Outputs:
[08-02-2020]-[01-00]

Obs.: Consider accepting the @mofi answer

It Wasn't Me
  • 2,145
  • 3
  • 15
  • 22