Thread: Increment a date by 1 day?

  1. #1
    Registered User
    Join Date
    Mar 2009

    Increment a date by 1 day?

    I have been trying to figure out how to increment a datetime by 1 day. For example 2009-03-31 13:00:00. I managed to write the following code, but I almost knew before I ran it what would happen. It icrements the day to 32 which does not exist obviously.

    #include <stdio.h>
    #include <time.h>
    int main()
    time_t currentTime;
    struct tm *ptm = localtime(&currentTime);
    printf("%d\n",(ptm->tm_mday) +1);
    return 0;
    Is there a way to convert a datetime to unix timestamp, add 86400 seconds, convert back to datetime?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Not tested, but you could add one to the tm_day member and run mktime (which I think is supposed to deal with odd things like the 32nd of January).

  3. #3
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    London, UK
    You should be able to just add 86400 seconds to currentTime before you convert it to ptm. I haven't tested that yet though.

    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    As tabstop suggests, use mktime() on what you're doing at the moment, and it will automatically normalise the time for you.

    So 32/01 becomes 01/02
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Mar 2009
    OK! mktime fixed it. Thanks for helping!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Advancing day by day until it matches a second date
    By nhubred in forum C++ Programming
    Replies: 1
    Last Post: 05-30-2009, 08:55 AM
  2. Determing the day for a given date
    By misplaced in forum C++ Programming
    Replies: 11
    Last Post: 10-10-2004, 07:13 PM
  3. Getting the Following Date
    By BB18 in forum C Programming
    Replies: 2
    Last Post: 10-10-2004, 12:39 PM
  4. debug program
    By new_c in forum C Programming
    Replies: 3
    Last Post: 03-18-2002, 11:50 PM
  5. Simplified code
    By soonerfan in forum C Programming
    Replies: 2
    Last Post: 12-05-2001, 03:50 PM