How to get a date in C yesterday?

I want to get yesterday date in char format in the format: YYYYMMDD (without a slash, etc.).

I use this code to get today's date:

time_t now;

struct tm  *ts;  
char yearchar[80]; 

now = time(NULL);  
ts = localtime(&now);

strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts);

How can I adapt this code so that it generates yesterday's date instead of today?

Many thanks.

+3
source share
7 answers

The function mktime()normalizes struct tmwhich you pass, so all you need to do is the following:

now = time(NULL);
ts = localtime(&now);
ts->tm_mday--;
mktime(ts); /* Normalise ts */
strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts);
+7
source

how about adding

now = now - (60 * 60 * 24)

It is not possible to execute some VERY rare corner cases (for example, during leapseconds), but you need to do what you want 99.999999% of the time.

+5
source

time(NULL);. :

now = time(NULL);

:

now = time(NULL) - (24 * 60 * 60);
+2

,

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
 
int main(void)
{
    char yestDt[9];
    time_t now = time(NULL);
    now = now - (24*60*60);
    struct tm *t = localtime(&now);
    sprintf(yestDt,"%04d%02d%02d", t->tm_year+1900, t->tm_mday,t->tm_mon+1);
    printf("Target String: \"%s\"", yestDt);
    return 0;
}
+2

. , Tyler - (24*60*60*1000), time (3) . struct tm. .

: , - (3) . . struct tm.

0

ts, strftime. tm_mday. :

/**
 * If today is the 1st, subtract 1 from the month
 * and set the day to the last day of the previous month
 */
if (ts->tm_mday == 1)
{
  /**
   * If today is Jan 1st, subtract 1 from the year and set
   * the month to Dec.
   */
  if (ts->tm_mon == 0)
  {
    ts->tm_year--;
    ts->tm_mon = 11;
  }
  else
  {
    ts->tm_mon--;
  }

  /**
   * Figure out the last day of the previous month.
   */
  if (ts->tm_mon == 1)
  {
    /**
     * If the previous month is Feb, then we need to check 
     * for leap year.
     */
    if (ts->tm_year % 4 == 0 && ts->tm_year % 400 == 0)
      ts->tm_mday = 29;
    else
      ts->tm_mday = 28;
  }
  else
  {
    /**
     * It either the 30th or the 31st
     */
    switch(ts->tm_mon)
    {
       case 0: case 2: case 4: case 6: case 7: case 9: case 11:
         ts->tm_mday = 31;
         break;

       default:
         ts->tm_mday = 30;
    }
  }
}
else
{
  ts->tm_mday--;
}

: , 1, (, , , ) 0.

0
time_t now;
int day;

struct tm  *ts;  
char yearchar[80]; 

now = time(NULL);  
ts = localtime(&now);
day = ts->tm_mday;

now = now + 10 - 24 * 60 * 60;
ts = localtime(&now);
if (day == ts->tm_mday)
{
  now = now - 24 * 60 * 60;
  ts = localtime(&now);
}

strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts);

.

0

Source: https://habr.com/ru/post/1786705/


All Articles