Setting a windows batch file variable to the day of the week

后端 未结 17 1989
南方客
南方客 2020-11-27 20:14

I have a windows batch file that runs daily. Wish to log data into a file and want to rotate it (i.e. having at most the last 7 days worth of data).

Looked into the

17条回答
  •  醉酒成梦
    2020-11-27 20:42

    Another spin on this topic. The below script displays a few days around the current, with day-of-week prefix.

    At the core is the standalone :dpack routine that encodes the date into a value whose modulo 7 reveals the day-of-week per ISO 8601 standards (Mon == 0). Also provided is :dunpk which is the inverse function:

    @echo off& setlocal enabledelayedexpansion
    rem 10/23/2018 daydate.bat: Most recent version at paulhoule.com/daydate
    rem Example of date manipulation within a .BAT file.
    rem This is accomplished by first packing the date into a single number.
    rem This demo .bat displays dates surrounding the current date, prefixed
    rem with the day-of-week.
    
    set days=0Mon1Tue2Wed3Thu4Fri5Sat6Sun
    call :dgetl y m d
    call :dpack p %y% %m% %d%
    for /l %%o in (-3,1,3) do (
      set /a od=p+%%o
      call :dunpk y m d !od!
      set /a dow=od%%7
      for %%d in (!dow!) do set day=!days:*%%d=!& set day=!day:~,3!
      echo !day! !y! !m! !d!
    )
    exit /b
    
    
    rem gets local date returning year month day as separate variables
    rem in: %1 %2 %3=var names for returned year month day
    :dgetl
    setlocal& set "z="
    for /f "skip=1" %%a in ('wmic os get localdatetime') do set z=!z!%%a
    set /a y=%z:~0,4%, m=1%z:~4,2% %%100, d=1%z:~6,2% %%100
    endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b
    
    
    rem packs date (y,m,d) into count of days since 1/1/1 (0..n)
    rem in: %1=return var name, %2= y (1..n), %3=m (1..12), %4=d (1..31)
    rem out: set %1= days since 1/1/1 (modulo 7 is weekday, Mon= 0)
    :dpack
    setlocal enabledelayedexpansion
    set mtb=xxx  0 31 59 90120151181212243273304334& set /a r=%3*3
    set /a t=%2-(12-%3)/10, r=365*(%2-1)+%4+!mtb:~%r%,3!+t/4-(t/100-t/400)-1
    endlocal& set %1=%r%& exit /b
    
    
    rem inverse of date packer
    rem in: %1 %2 %3=var names for returned year month day
    rem %4= packed date (large decimal number, eg 736989)
    :dunpk
    setlocal& set /a y=%4+366, y+=y/146097*3+(y%%146097-60)/36524
    set /a y+=y/1461*3+(y%%1461-60)/365, d=y%%366+1, y/=366
    set e=31 60 91 121 152 182 213 244 274 305 335
    set m=1& for %%x in (%e%) do if %d% gtr %%x set /a m+=1, d=%d%-%%x
    endlocal& set /a %1=%y%, %2=%m%, %3=%d%& exit /b
    

提交回复
热议问题