Question

Task given: I need to get the next date from the current date (d, m, y) and return a tuple of integer (day, month, year).

Here's my code:

def next_date(d, m, y):
    if m == 12 and d == 31:
        d, m, y = 1, 1, y+1
    elif m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m== 10:
        if d == 31:
            d, m, y = 1, m+1, y
        elif d > 31:
            return 'No such date exist'
        else:
            d, m, y = d + 1, m, y
    elif m== 4 or m == 6 or m == 9 or m == 11:
        if d == 30:
            d, m, y = 1, m+1, y
        elif d > 30:
            return 'No such date exist'
        else:
            d, m, y = d+1, m, y
    elif m == 2:
        if is_leap_year(y) and d == 29:
            d, m, y = 1, 3, y
        elif is_leap_year(y) and d == 28:
            d,m,y = 29, m, y
        if not is_leap_year(y):
           if d == 28:
                d, m, y = 1, 3, y
            if d > 28:
                return 'No such date exist'

    else:
        d, m, y = d + 1, m, y
    return (d,m,y)

Is there a simpler code than this such that it will not give me an infinite loop? Thanks a lot.

Was it helpful?

Solution

If you are not allowed to use a library, you can use this shorter one:

def next_date(d, m, y):
    days = [31,28,31,30,31,30,31,31,30,31,30,31]
    if is_leap_year(y):
        days[1] = 29

    if d < 1 or d > days[m-1] or m < 1 or m > 12:
        return "No such date exist"

    d += 1
    if d > days[m-1]:
        d, m = 1, m+1
        if m > 12:
            d, m, y = 1, 1, y+1

    return (d,m,y)

You can test using the following:

print next_date(10, 2, 2014)
print next_date(28, 2, 2014)
print next_date(29, 2, 2014)
print next_date(31, 12, 2014)

Also, here is a simple implementation for is_leap_year which you did not implement:

def is_leap_year(y):
    return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)

OTHER TIPS

import datetime

def next_date(d, m, y):
    given_day = datetime.date(y, m, d)
    next_day = today + datetime.timedelta(days=1)
    return next_day.day, next_day.month, next_day.year

A little standard library, and your life is way easier :D Check THIS out.

Try using the datetime module of Python:

import datetime

def next_date(d, m, y):
    date = datetime.datetime(d,m,y)
    date += datetime.timedelta(days=1)
    return (date.day, date.month, date.year)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top