How to get the system date time format?

2019-05-30 06:09发布

I have a batch file that does some operations based on the date. It extracts the day, month and year and then creates a file with these variables. The trouble is the date format is different on different machines (dd/mm/yyyy, mm/dd/yyyy, ddd dd/mm/yyyy etc.). Is there a way to extract the date format first and then create the variables based on the extracted format in a batch file.

2条回答
迷人小祖宗
2楼-- · 2019-05-30 06:45

try this:

@ECHO OFF &SETLOCAL

call:main
ECHO %ERRORLEVEL%
goto:eof

:main
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=3" %%A IN ('REG Query "HKEY_CURRENT_USER\Control Panel\International" /v sDate') DO SET lim=%%A
FOR /F "tokens=2,*" %%A IN ('REG Query "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate') DO SET sdf=%%B
SET now=%date%
IF DEFINED lim (
    FOR /F %%D IN ("!lim!") DO (
        SET sdf=!sdf:%%~D= !
        SET now=!date:%%~D= !
    )
)
FOR %%A IN ("jan=1" "feb=2" "mar=3" "apr=4" "may=5" "jun=6" "jul=7" "aug=8" "sep=9" "oct=10" "nov=11" "dec=12") DO SET now=!now:%%~A!
FOR %%A IN (m o n t u e w d h r f i s a) DO SET now=!now:%%A=!
FOR %%A IN (%sdf%) DO (
    SET tester=%%A
    IF "!tester:ffffd=!"=="!tester!" (
        IF NOT "!tester:d=!"=="!tester!" (
            SET ndf=!ndf! tday
        ) ELSE (
            IF NOT "!tester:m=!"=="!tester!" (
                SET ndf=!ndf! tmonth
            ) ELSE (
                SET ndf=!ndf! tyear
            )
        )
    )
)
CALL :Match %now%
FOR %%A IN (tyear tmonth tday) DO IF NOT DEFINED %%A (
    >&2 ECHO An Error Occured - Check if it is EVEN POSSIBLE to work out what
    >&2 ECHO the date is from the %%date%% variable^("%date%"^).
    ENDLOCAL
    EXIT /B 1
)
IF %tyear% LSS 99 SET tyear=20%tyear%
IF NOT "%tmonth:~0,1%"=="0" IF %tmonth% LSS 10 SET tmonth=0%tmonth%
IF NOT "%tday:~0,1%"=="0" IF %tday% LSS 10 SET tday=0%tday%
ENDLOCAL & EXIT /B %tyear%%tmonth%%tday%


:Match
FOR %%A IN (%ndf%) DO (
    CALL SET %%A=%%1
    SHIFT
)

This is pure batch and works on all XP systems without wmic, Vista, Win7 & 8.


Echo the date format:

FOR /F "tokens=2,*" %%A IN ('REG Query "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate') do set "DateFormat=%%B"
echo %DateFormat%
查看更多
可以哭但决不认输i
3楼-- · 2019-05-30 07:01

This should work on any machine from XP Pro and later.

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set "dt=%%a"
set "YYYY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%"
set "Min=%dt:~10,2%"
set "Sec=%dt:~12,2%"

set datestamp=%YYYY%%MM%%DD%
set timestamp=%HH%%Min%%Sec%
set fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
查看更多
登录 后发表回答