3
Contributors
2
Replies
21
Views
1 Year
Discussion Span
Last Post by deceptikon
0

http://www.cplusplus.com/reference/ctime/localtime/

The example above gives TODAY's date/time. To get yesterday's data, subtract the number of seconds in a day, as below. In addition, using the strftime function, you can isolate just the date.

http://www.cplusplus.com/reference/ctime/strftime/

/* localtime example */
#include <stdio.h>      /* puts, printf */
#include <time.h>       /* time_t, struct tm, time, localtime */

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  const unsigned int NUM_SECONDS_IN_DAY = 3600 * 24;
  time (&rawtime);
  rawtime -= NUM_SECONDS_IN_DAY;
  timeinfo = localtime (&rawtime);
  printf ("Yesterday's local time and date: %s", asctime(timeinfo));

  // only show date
  char buffer[100];
  strftime (buffer,100,"Yesterday's date was %x.",timeinfo);
  puts (buffer);

  return 0;
}

Edited by AssertNull

1

The calculations are unnecessary. mktime can be used to normalize the contents of a tm structure to the correct date and time after manual modifications.

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    time_t now = time(0);
    tm *date = localtime(&now);

    --date->tm_mday; // Move back one day
    mktime(date); // Normalize

    cout << asctime(date) << '\n';
}
Votes + Comments
I like this approach.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.