如何在批处理文件中获取一年中的某天
如何从Windows批处理文件中从当前日期获取一年中的哪一天?
How can I get the day of year from the current date in a Windows batch file?
我尝试过
SET /A dayofyear=(%Date:~0,2%*30.5)+%Date:~3,2%
但是它不适用于leap年,并且总是要几天的时间.我不想使用任何第三方可执行文件.
But it does not work with leap years, and it is always off by a few days. I would not like to use any third-party executables.
If you want the Julian Day Number, you may use the method posted in my accepted answer given at previous link. However, the "day of year" is just a number between 1 and 365 (366 for leap years). The Batch file below correctly calculate it:
@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
.
Note: This relies on the date format MM/DD/YYYY
.
编辑2020/08/10 :添加了更好的方法
我修改了方法,因此现在使用wmic
来获取日期.新方法也缩短了,但没有更简单! ;)
:
I modified the method so it now uses wmic
to get the date. The new method is also shorten, but no simpler! ;)
:
@echo off
setlocal
set "daysPerMonth=0 31 28 31 30 31 30 31 31 30 31 30"
for /F "tokens=1-3" %%a in ('wmic Path Win32_LocalTime Get Day^,Month^,Year') do (
set /A "dayOfYear=%%a, month=%%b, leap=!(%%c%%4)*(((month-3)>>31)+1)" 2>NUL
)
set /A "i=1, dayOfYear+=%daysPerMonth: =+(((month-(i+=1))>>31)+1)*%+leap"
echo %dayOfYear%