1

I'm looking for an algorithm to find the date of a day in the future, which is in N days from today.

My main problem is how to deal with leap years in the middle.

user7116
  • 63,008
  • 17
  • 141
  • 172
Saba Jamalian
  • 750
  • 2
  • 10
  • 24

7 Answers7

4

If I take your question correctly, your best option is to do the following:

  1. Convert a date into a number, where the number signifies the number of days since a specific date
  2. Add N to that number
  3. Convert the results back into a date

You can do this using the julian day number for a date.

See the Wikipedia article on Julian Day Number (JDN) for more information.

Having said that, if you're actually using a modern programming language, most have facilities to deal with dates already, such as Java, C#/.NET, Python, etc.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
1

This is highly dependent on what language and frameworks you are using for your development, as most frameworks have some way to handle this. For example, in .NET, this is very easy:

DateTime futureDate = DateTime.Today.AddDays(numberOfDaysInFuture);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

Here is the ruby code that is used at http://reqr.net/cal to calculate day offsets: https://gist.github.com/910427

The algorithm itself is language agnostic and only uses primitive types.

Nick Moore
  • 15,547
  • 6
  • 61
  • 83
0

Seconds are your friend. Pseudocode for whatever language you are using:

seconds_since_1970_to_date(date_to_seconds_since_1970(currentdate) + N * 86400)

drysdam
  • 8,341
  • 1
  • 20
  • 23
0

Transact-SQL (MS SQL Server) offers the DATEADD function. For example:

DECLARE @days int;
DECLARE @datetime datetime;
SET @days = 365;
SET @datetime = '2000-01-01 01:01:01.111'; /* 2000 was a leap year */
SELECT DATEADD(day, @days, @datetime);

--RESULT: 2000-12-31 01:01:01.110

Nick Silberstein
  • 833
  • 2
  • 8
  • 24
0

Since you are looking to a C solution, check out if ctime.h doesn't fit your needs before reimplementing everything yourself.

hugomg
  • 68,213
  • 24
  • 160
  • 246