Thread: Get yesterdays date from time_t?

  1. #1
    Registered User
    Join Date
    Nov 2010

    Get yesterdays date from time_t?

    I have a time_t structure with the current date/time.

    What I want is to work out yesterday's date from this. Just subtracting one from the day is not enough as it needs to take the first of the month into account and also the first of Jan into account. As month and/or year could change under these circumstances.

    Obviously I can write code to handle all these cases and wrap it up in a function but I just wondered if there already existed an easier way of doing this?

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Hannover, Germany
    time_t is not a structure, it's just a plain value holding the number of seconds elapsed since 1/1/1970. You could subtract 60*60*24 from it, then you have the number that would have been returned yesterday.

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
           struct tm *localtime(const time_t *timep);
           time_t mktime(struct tm *tm);
    Use localtime() to break a time into it's individual parts.

    Then do something like
    var.tm_mday--; // yesterday

    Then do mktime() to get back to where you started (but one day earlier)

    There is also gmtime(), if you want to avoid potential unpleasantness around daylight saving days.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. libcurl experience and question
    By Dino in forum C Programming
    Replies: 6
    Last Post: 10-26-2009, 02:07 PM
  2. 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
  3. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  4. CDate Class - handle date manipulation simply
    By LuckY in forum C++ Programming
    Replies: 5
    Last Post: 07-16-2003, 08:35 AM