Reputation: 73
Below code some time works fine but some time showing error. In MM case previously my output was 8 instead of 08. But now am getting 08 as a string with error Invalid number. Numeric constants are either decimal (17), hexadecimal (0x11), or octal (021).
echo off
CD /d C:\Windows\System32\wbem\
FOR /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
SET /a YYYY=%MyDate:~0,4%
SET /a MM=%MyDate:~4,2%
SET /a DD=%MyDate:~6,2%
echo %YYYY%
echo %MM%
echo %DD%
Upvotes: 0
Views: 530
Reputation: 79983
SET /a MM=1%MyDate:~4,2%-100
SET /a DD=1%MyDate:~6,2%-100
is the standard method of overcoming this problem.
The reverse, to obtain a 2-character leading-zero-filled version, is
set /a MM+=100 set "MM=%MM:~-2%"
Upvotes: 1
Reputation: 49086
Windows command interpreter uses the C/C++ function strtol with value 0
for third function parameter base
. This means any number string starting with 0 is interpreted as octal number. 08
and 09
are not valid octal numbers as the octal system has only the digits 0 to 7.
The solution is not using an arithmetic expression and instead use just string substitutions:
@echo off
setlocal EnableExtensions
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "MyDate=%%I"
set "Year=%MyDate:~0,4%"
if "%MyDate:~4,1%" == "0" ( set "Month=%MyDate:~5,1%" ) else set "Month=%MyDate:~4,2%"
if "%MyDate:~6,1%" == "0" ( set "Day=%MyDate:~7,1%" ) else set "Day=%MyDate:~6,2%"
echo Year: %Year%
echo Month: %Month%
echo Day: %Day%
endlocal
This batch code outputs:
Year: 2017
Month: 8
Day: 24
The UTF-16 Little Endian encoded output of used WMIC command is:
LocalDateTime=20170824150309.315000+120
Only 20170824150309
is assigned to environment variable MyDate
because of tokens=2 delims==.
which is processed further by the next 3 command lines after FOR command line using just string substitutions and not arithmetic expressions which is no help here to remove a leading zero.
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 /?
set /?
wmic /?
wmic os /?
wmic os get /?
wmic os get localdatetime /?
Upvotes: 0