0

我正在创建一个批处理文件来运行一些备份。但是当我尝试用当前日期时间为文件命名时,它会给出一个奇怪的结果。

我在用着:

backup.backup_%DATE:~10,4%%DATE:~7,2%%DATE:~4,2%_%time:~0,2%%time:~3,2%%time:~6,2%.backupfile

结果:backup.backup_0130-5-_101151.backupfile

有谁知道如何解决这一问题?

4

4 回答 4

2

我认为您应该使用wmic而不是dateandtime来获取当前日期和时间,而不受区域设置的影响

@echo off
SETLOCAL EnableDelayedExpansion


for /f "skip=1 tokens=1-6 delims= " %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
    IF NOT "%%~f"=="" (
        set /a FormattedDate=10000 * %%f + 100 * %%d + %%a
        set FormattedDate=!FormattedDate:~0,4!!FormattedDate:~-4,2!!FormattedDate:~2,2!
        set /a FormattedTime=%%b * 10000 + %%c * 100 + %%e
        set FormattedTime=!FormattedTime:~0,2!!FormattedTime:~-4,2!!FormattedTime:~-2,2!
    )
)

echo backup.backup_!FormattedDate!_!FormattedTime!
PAUSE

上面的代码将以以下格式命名文件:

备份.backupYYYYMMDD_HHMMSS

例如backup.backup_20131013_163800

希望这可以帮助。

于 2013-10-25T08:39:32.050 回答
2

尝试这个:

@ECHO OFF &SETLOCAL
for /f "skip=1delims=." %%a in ('wmic os get localdatetime') do if not defined DateTime set "DateTime=%%a"
echo(backup.backup_%DateTime:~0,8%_%DateTime:~8%
于 2013-10-25T08:57:54.937 回答
1

如果您必须在批处理文件中多次使用它,将它作为一个函数很好。这可能会有所帮助:

:GetFileDateTime Format ret
@echo off & setlocal
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & 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%"
( ENDLOCAL
    if /i "%~1"=="DT" set "%~2=%datestamp% %timestamp%"
    if /i "%~1"=="TD" set "%~2=%timestamp% %datestamp%" 
    if /i "%~1"=="D" set "%~2=%datestamp%"
    if /i "%~1"=="T" set "%~2=%timestamp%"
    if /i "%~1"=="F" set "%~2=%fullstamp%"
)
exit /b


Usage Example:

call :GetFileDateTime TD timedate
echo %timedate%

call :GetFileDateTime D date
echo %date%
于 2013-10-25T12:35:15.330 回答
0

我还建议将 Wmic 用于 XP pro 及更高版本。我经常发布这个片段:

此代码的前四行将为您提供 XP Pro 及更高版本中可靠的 YY DD MM YYYY HH Min Sec 变量。

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & 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-10-25T10:29:02.880 回答