Can't remember if this was posted or not... I can't seem to find it...
def calculateAge(self, date):
'''Calculates the age and days until next birthday
from the given birth date to display in the results'''
returnStr = ''
try:
for i in './- ':
if (date.find(i) != -1):
date = date.split(i)
break;
birthdate = datetime.date(int(date[0]), int(date[1]), int(date[2]))
today = datetime.date.today()
if (today.month > birthdate.month):
nextYear = datetime.date(today.year + 1, birthdate.month, birthdate.day)
elif (today.month < birthdate.month):
nextYear = datetime.date(today.year, today.month + (birthdate.month - today.month), birthdate.day)
elif (today.month == birthdate.month):
if (today.day > birthdate.day):
nextYear = datetime.date(today.year + 1, birthdate.month, birthdate.day)
elif (today.day < birthdate.day):
nextYear = datetime.date(today.year, birthdate.month, today.day + (birthdate.day - today.day))
elif (today.day == birthdate.day):
nextYear = 0
age = today.year - birthdate.year
if nextYear == 0: #if today is the birthday
returnStr = '%d, days until %d: %d' % (age, age+1, 0)
else:
daysLeft = nextYear - today
returnStr = '%d, days until %d: %d' % (age, age+1, daysLeft.days)
except:
returnStr = 'date not entered or format incorrect'
return returnStr