Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to add or subtract days from a date?

Tags:

I'm trying to write a Date class in an attempt to learn C++.

I'm trying to find an algorithm to add or subtract days to a date, where Day starts from 1 and Month starts from 1. It's proving to be very complex, and google doesn't turn up much,

Does anyone know of an algorithm which does this?

like image 619
bcoughlan Avatar asked Feb 26 '10 19:02

bcoughlan


People also ask

How do you add or subtract days from a date in python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

How do I subtract 6 days from a date in SQL?

The DATE_SUB() function subtracts a time/date interval from a date and then returns the date.


1 Answers

The easiest way is to actually write two functions, one which converts the day to a number of days from a given start date, then another which converts back to a date. Once the date is expressed as a number of days, it's trivial to add or subtract to it.

You can find the algorithms here: http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html

like image 74
Mark Ransom Avatar answered Sep 22 '22 13:09

Mark Ransom