如何获取昨天的C日期?

问题描述 投票:3回答:7

我想以YYYYMMDD的格式将昨天的日期转换为字符,(不带斜杠等)。

我正在使用此代码获取今天的日期:

time_t now;

struct tm  *ts;  
char yearchar[80]; 

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

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

我将如何修改此代码,以便它生成昨天而不是今天的日期?

非常感谢。

c date strftime localtime
7个回答
7
投票

mktime()函数将对传递给它的struct tm进行归一化(即,它将把2020/2/0之类的超出范围的日期转换为等效的2020/1/31)-所以所有您需要做的是:

time_t now;
struct tm  *ts;  
char yearchar[80]; 

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

5
投票

如何添加

now = now - (60 * 60 * 24)

[在某些极少数情况下可能会失败(例如,在leap秒内失败,但应该在99.999999%的时间内完成您想要的操作。


2
投票

只需从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;
}

0
投票

您非常接近。首先,泰勒的解决方案将几乎起作用-由于time(3)返回毫秒,因此您需要使用(24*60*60*1000)。但是看看struct tm。它具有日期所有组成部分的字段。

更新:该死,我的错误-time(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's 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);

也将使用leap秒。

© www.soinside.com 2019 - 2024. All rights reserved.