Reputation: 760
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
Reputation: 292
see
Arithmetics on calendar dates in C or C++ (add N days to given date)
https://en.wikipedia.org/wiki/C_date_and_time_functions
http://www.cplusplus.com/reference/ctime/
http://en.cppreference.com/w/c/chrono
Upvotes: 0
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
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
Reputation: 391724
If I take your question correctly, your best option is to do the following:
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
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
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
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