Saba Jamalian
Saba Jamalian

Reputation: 760

Find the date in N days by now

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.

Upvotes: 1

Views: 1468

Answers (7)

hugomg
hugomg

Reputation: 69984

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

Upvotes: 0

Nick Silberstein
Nick Silberstein

Reputation: 833

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

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391724

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.

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564931

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);

Upvotes: 1

drysdam
drysdam

Reputation: 8637

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

seconds_since_1970_to_date(date_to_seconds_since_1970(currentdate) + N * 86400)

Upvotes: 0

Nick Moore
Nick Moore

Reputation: 15857

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.

Upvotes: 0

Related Questions