Can anyone tell me how to calculate yesterday's date using c++?

Recommended Answers

All 2 Replies

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.

/* 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;

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';
commented: I like this approach. +5
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.