1

我有一个批处理文件,它根据日期执行一些操作。它提取日、月和年,然后使用这些变量创建一个文件。问题是不同机器上的日期格式不同(dd/mm/yyyy、mm/dd/yyyy、ddd dd/mm/yyyy 等)。有没有办法先提取日期格式,然后根据批处理文件中提取的格式创建变量。

4

2 回答 2

3

这应该适用于 XP Pro 及更高版本的任何机器。

@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
于 2013-08-05T14:15:38.400 回答
1

尝试这个:

@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:ddd=!"=="!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
)

这是纯批处理,适用于所有没有wmic、Vista、Win7 和 8 的 XP 系统。


回显日期格式:

FOR /F "tokens=2,*" %%A IN ('REG Query "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate') do set "DateFormat=%%B"
echo %DateFormat%
于 2013-08-05T08:58:51.000 回答