Days between dates: Difference between revisions

From Rosetta Code
Content added Content deleted
(Initial Creation of the simple days between dates task.)
 
mNo edit summary
Line 8: Line 8:
https://stackoverflow.com/questions/12862226/the-implementation-of-calculating-the-number-of-days-between-2-dates
https://stackoverflow.com/questions/12862226/the-implementation-of-calculating-the-number-of-days-between-2-dates


Several examples in C including an origin based algorithm can be foud here:http://www.sunshine2k.de/articles/coding/datediffindays/calcdiffofdatesindates.html
This example is also described on the following page as the origin based algorithm implemented in c:http://www.sunshine2k.de/articles/coding/datediffindays/calcdiffofdatesindates.html.




Line 17: Line 17:
import sys
import sys


''' Difference between two dates = g(y2,m2,d2) - g(y1,m1,d1) '''
''' Difference between two dates = g(y2,m2,d2) - g(y1,m1,d1)
Where g() gives us the Gregorian Calendar Day
'''


def days( y,m,d ):
def days( y,m,d ):

Revision as of 11:30, 30 September 2019

Task
Days between dates
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Calculate the number of days between two dates. Date input should be in the form YYYY-MM-DD.

The initial example in python is derived from discussion at: https://stackoverflow.com/questions/12862226/the-implementation-of-calculating-the-number-of-days-between-2-dates

This example is also described on the following page as the origin based algorithm implemented in c:http://www.sunshine2k.de/articles/coding/datediffindays/calcdiffofdatesindates.html.


Python

<lang python>

  1. !/usr/bin/python

import sys

Difference between two dates = g(y2,m2,d2) - g(y1,m1,d1)

   Where g() gives us the Gregorian Calendar Day

def days( y,m,d ):

  we shift to march with (m*306 + 5)/10 
 m = (m + 9) % 12 
 y = y - m/10
 result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
 return result

def diff(one,two):

 [y1,m1,d1] = one.split('-')
 [y2,m2,d2] = two.split('-')
 # strings to integers
 year2 = days( int(y2),int(m2),int(d2))
 year1 = days( int(y1), int(m1), int(d1) )
 return year2 - year1

if __name__ == "__main__":

 one = sys.argv[1]
 two = sys.argv[2]
 print diff(one,two)

</lang>

Output:
python days-between.py 2019-01-01 2019-09-30
272