Tuesday, October 15, 2013

Windows Batch Script Date format: Set day of the year

Unfortunately there is no direct way to do so. You would need to perform some computation after parsing the date. Below is the script you can use:

@echo off
setlocal disabledelayedexpansion

set /a y=%date:~-4%
set /a m=%date:~-07,2%
set /a d=%date:~-10,2%

set /a w= %d% +(!(%y% %% 4)-!(%y% %% 100)+!(%y% %% 400))*(!((%m%-3)^&16))
set /a w=(%w%+(%m%-1)*30+2*(!((%m%-7)^&16))-1+((65611044^>^>(2*%m%))^&3))
echo %w%

One thing to note about using SET /A command is that it treats its values as an octal notation. To easily explain this, below is an excerpt from one of my searches in google (forgot where, if you know, please comment below so I can credit appropriately.)

“SET /A has a very unfortunate feature in that any number that has a leading 0 is treated as octal notation. So a value of 08 or 09 is not a valid number for SET /A, and will give the error message that you cited. To get the correct value you must represent the MINS as 8 or 9 (no leading 0). Note that 00 through 07 work fine because both octal and decimal interpretation yield the same value.”

Here is the octal and decimal values:


















Of course, you may simply remove the /A when you only want to get the values for y, m and d. But when using the 08 and 09 value in another date computation (eg. computing for the value of w above), they will still be interpreted as octal because of the SET /A used. To remedy the above issue, you can use:

Before:
set /a m=%date:~-07,2%
set /a d=%date:~-10,2%

Echoing  %m% - %d%  gives you 08 and 09.

After:
REM use the following to remove leading ZERO values:
set /a m=10000%date:~-07,2% %% 10000
set /a d=10000%date:~-10,2% %% 10000

Echoing  %m% - %d%  gives you 8 and 9.

No comments:

Post a Comment