Ricky Payne
Ricky Payne

Reputation: 149

Working out the date based on the day number

I'm sure this must be possible, but I wouldn't know where to start.

I need to be able to work out the date based on a number. The number is sequential, and will increase by one each day. So I can do as much as to get the number to be relevant to the number of the day of the year (i.e. Jan 1st would be day 1 etc.) But I need to be able to work out the date in ddmmyyyy format with any given number.

There are similar questions I've found relating to C++ and Java Script...

Can this be done in CMD?

Edit

I've just realised that the date will change depending on the year (i.e. leapyears)

For my script, the year will always be 2012, so I need to be able to work out the date based on the ordinal (I think thats the right way to describe it) day, for 2012 only.

Upvotes: 0

Views: 147

Answers (1)

GolezTrol
GolezTrol

Reputation: 116130

Code below gets the date from the current date. It's easy to change it to a fixed year of course.

I would love to say I wrote this all myself, but it is based on the code by Rob van der Woude. Take a look at the site. It has lots of date calculation functions all of them isolated in separate scripts instead of the fixed-purpose mess I made out of it. ;)

@echo off
:: Input: The number of days to add. You can make this a parameter 
:: too, if you want.
SET /A Days   = 20
echo %DATE:~-4%

:: Get 1 january of the current year
SET /A Year1  = %DATE:~-4% + 4800
SET MM=1
SET DD=1

:: Calculate the Julian date of that date.
SET /A Month1 = ( %MM% - 14 ) / 12
SET /A JDate  = 1461 * ( %Year1% + %Month1% ) / 4 + 367 * ( %MM% - 2 -12 * %Month1% ) / 12 - ( 3 * ( ( %Year1% + %Month1% + 100 ) / 100 ) ) / 4 + %DD% - 32075

:: Add the number of days
SET /A JDate  = %JDate% + %Days%

:: Calculate it back to year, month and day.
SET /A P      = %JDate% + 68569
SET /A Q      = 4 * %P% / 146097
SET /A R      = %P% - ( 146097 * %Q% +3 ) / 4
SET /A S      = 4000 * ( %R% + 1 ) / 1461001
SET /A T      = %R% - 1461 * %S% / 4 + 31
SET /A U      = 80 * %T% / 2447
SET /A V      = %U% / 11

:: SET /A GYear  = 100 * ( %Q% - 49 ) + %S% + %V%
SET /A GMonth = %U% + 2 - 12 * %V%
SET /A GDay   = %T% - 2447 * %U% / 80

:: Echo only month and day
echo %GMonth% %GDay%

:: Clean-up
FOR %%A IN (P Q R S T U V MM  DD JDate Year1 GDay GMonth GYear) DO SET %%A=

Upvotes: 2

Related Questions