如何在Windowsbatch file中从当前date中获得一年中的哪一天?
我努力了
SET /A dayofyear=(%Date:~0,2%*30.5)+%Date:~3,2%
但是它不适用于闰年,它总是会closures几天。 我不想使用任何第三方可执行文件。
如果你想要Julian Day号码,你可以使用前面链接给出的接受答案中公布的方法。 然而,“一年中的某一天”只是1到365之间的一个数字(闰年为366)。 下面的批处理文件正确计算它:
@echo off setlocal EnableDelayedExpansion set /A i=0, sum=0 for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do ( set /A i+=1 set /A accum[!i!]=sum, sum+=%%a ) set /A month=1%Date:~0,2%-100, day=1%Date:~3,2%-100, yearMOD4=%Date:~6,4% %% 4 set /A dayOfYear=!accum[%month%]!+day if %yearMOD4% equ 0 if %month% gtr 2 set /A dayOfYear+=1 echo %dayOfYear%
注意:这依赖于日期格式MM/DD/YYYY
。
@Aacini的答案有两个弱点(尽管对许多应用程序来说已经足够了,毕竟这是一个很好的方法):
MM/DD/YYYY
格式,但是%Date%
是依赖于区域的; 以下是@Aacini批处理脚本的修订版本(在解释性说明中描述):
@echo off setlocal EnableDelayedExpansion set /A i=0, sum=0 rem accumulate day-offsets for every month in %accum[1...12]% for %%a in (31 28 31 30 31 30 31 31 30 31 30 31) do ( set /A i+=1 set /A accum[!i!]=sum, sum+=%%a ) rem check for availability of alternative date value given via (1st) command line argument, rem just for convenient batch testing if "%1"=="" ( rem WMIC retrieves current system date/time in standardised format; rem parse its output by FOR /F, then store it in %CurrDate% for /F "tokens=2 delims==" %%D in ('wmic OS GET LocalDateTime /VALUE ^| find "="') do ( set CurrDate=%%D ) ) else ( rem apply date value from command line in YYYYMMDD format (not checked for validity) set CurrDate=%1 ) rem extract %month% and %day%; set /A month=1%CurrDate:~4,2%-100, day=1%CurrDate:~6,2%-100 rem compute several moduli needed for determining whether year is leap year set /A yearMOD4=%CurrDate:~0,4% %% 4 set /A yearMOD100=%CurrDate:~0,4% %% 100, yearMOD400=%CurrDate:~0,4% %% 400 rem calculate %dayOfYear% as it were not a leap year set /A dayOfYear=!accum[%month%]!+day rem adapt %dayOfYear% only in case %month% is past February (29th) if %month% gtr 2 ( rem check for leap year and adapt %dayOfYear% accordingly if %yearMOD4% equ 0 set /A dayOfYear+=1 if %yearMOD400% neq 0 if %yearMOD100% equ 0 set /A dayOfYear-=1 ) rem compound statement to let %dayOfYear% survive SETLOCAL/ENDLOCAL block endlocal & set dayOfYear=%dayOfYear% rem return result echo %dayOfYear%