如何在批处理文件中比较两个日期?
if %%newdate geq %olddate% _do smth_
无法工作。
在这种情况下,我发现27.05.2013
大于 15.07.2013
并且14.07.2013
小于 15.07.2013
Zhenya
如何在批处理文件中比较两个日期?
if %%newdate geq %olddate% _do smth_
无法工作。
在这种情况下,我发现27.05.2013
大于 15.07.2013
并且14.07.2013
小于 15.07.2013
Zhenya
尝试这个:
set "sdate1=%olddate:~-4%%olddate:~3,2%%olddate:~0,2%"
set "sdate2=%newdate:~-4%%newdate:~3,2%%newdate:~0,2%"
if %sdate1% GTR %sdate2% (goto there) else echo here
if %sdate1% GTR %sdate2% echo %olddate% is greater than %newdate%
。 - foxidrive在处理日期时,应始终使用ISO格式(yyyy-MM-dd HH:mm:ss)。这样可以避免歧义,不受地区影响,并且可以按照时间顺序排序,您可以轻松将其作为CMD文件中的字符串进行比较。
For /F "tokens=1,2 delims==" %%i in ('wmic os get LocalDateTime /VALUE') do (if .%%i EQU .LocalDateTime set ldt=%%j)
set CURRENT_DATE=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%
set CURRENT_TIME=%ldt:~8,2%:%ldt:~10,2%:%ldt:~12,2%
CURRENT_DATE in yyyy-MM-dd format
CURRENT_TIME in HH:mm:ss format
call :date_to_number %date1% date1
call :date_to_number %date2% date2
if %date1% GEQ %date2% echo date1 is bigger
goto :eof
:date_to_number
setlocal
if "%~1" EQU "" goto :eof
for /f "tokens=1,2,3 delims=." %%D in ("%~1") do (
set "the_date=%%F%%E%%D"
)
endlocal & if "%~2" neq "" (set %~2=%the_date%) else echo %the_date%
goto :eof
但这仅适用于日期格式为DD.MM.YYYY的情况。
我遇到了一个问题,我想找到密码已过期或即将过期的用户。
首先,Windows 10已更改了%date%变量的格式,因此它看起来与以前的版本不同。因此,“echo %date%” 的输出如下所示:“Thu 05/09/19”,因此我使用这个一行代码将今天的日期转换为yyyymmdd格式。
set today=20%date:~-2%%date:~4,2%%date:~7,2%
(today = 20190509)
这很容易,因为我们知道每个月和日都有两位数字。
现在,如果您正在使用的“日期格式”没有在单个数字月份和日期前面填充前导零,那么您将不得不自己填充它们。 例如,命令输出:net user %username% /domain 的输出看起来像“5/9/19”,请注意缺少的零...
所以你可以用几种不同的方法提取它。最简单的方法是分别获取每个字段,将零放在月份和日期变量前面,然后只获取它们的最后两位数字。 这样5就变成了05,12就变成了012,然后又回到了12。
for /f "tokens=3-5 delims=/ " %%a in ('net user %username% /domain ^|find /i "Password expires"') do (
set mm=0%%a& set dd=0%%b& set yyyy=20%%c
set expires=!yyyy!!mm:~-2!!dd:~-2!
if NOT !expires! GTR %today% echo Password has expired and needs to be changed.
I create a simple c program i call newest.exe. Below is the source code.
#include <stdio.h>
#include <sys/stat.h>
#include <time.h>
// syntax: newest file1 file2
//
// if age1 = age2, prints 0 age1 age2
// if age1 < age2, prints 1 age1 age2
// if age1 > age2, prints 2 age1 age2
// where
// age1 is age of file1 is seconds.
// age2 is age of file2 is seconds.
//
// To capture the output in a DOS bat file use:
// for /f "tokens=1-3" %%i in ('%srcPath%\newest.exe %src% %des%') do (
// set newest=%%i
// set age1=%%j
// set age2=%%k
// )
int main(int argc, char **argv)
{
struct stat fileStat;
time_t now;
long age1, age2;
if(argc != 3)
{
printf("syntax: %s File1 File2\n", argv[0]);
return 1;
}
now = time(NULL);
if(stat(argv[1],&fileStat) < 0) return 1;
age1 = now - fileStat.st_mtime;
if(stat(argv[2],&fileStat) < 0) return 1;
age2 = now - fileStat.st_mtime;
if( age1 == age2 )
printf("0 %d %ld\n", age1, age2);
else if( age1 < age2 )
printf("1 %d %ld\n", age1, age2);
else
printf("2 %d %ld\n", age1, age2);
return 0;
}