如何在 C 语言中获取昨天的日期?
我想将昨天的日期转换为以下格式的字符:YYYYMMDD(没有斜线点等)。
我正在使用此代码来获取今天的日期:
time_t now;
struct tm *ts;
char yearchar[80];
now = time(NULL);
ts = localtime(&now);
strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts);
如何调整此代码以使其生成昨天的日期而不是今天的日期?
非常感谢。
I am wanting to get yesterday's date into a char in the format: YYYYMMDD (with no slashes dots etc.).
I am using 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 would I adapt this code so that it is generating yesterday's date instead of today's?
Many Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
mktime() 函数将规范化您传递给它的 struct tm(即,它将像 2020/2/0 这样的超出范围的日期转换为内部日期)范围相当于 2020/1/31) - 所以您需要做的就是这样:
The
mktime()
function will normalise thestruct tm
that you pass it (ie. it will convert out-of-range dates like 2020/2/0 into the in-range equivalent 2020/1/31) - so all you need to do is this:在一些非常罕见的极端情况下(例如在闰秒期间)可能会
失败,但应该在 99.999999% 的时间内执行您想要的操作。
how about adding
Might fail in some VERY rare corner cases (e.g. during leapseconds) but should do what you want 99.999999% of the time.
只需从
time(NULL);
中减去一天的秒数就可以了。将此行:更改为:
Simply subtracting one day's worth of seconds from
time(NULL);
should do. Change this line:to this:
请尝试这个代码
Please try this code
你已经很接近了。首先,泰勒的解决方案几乎可以工作——您需要使用
(24*60*60*1000)
,因为 time(3) 返回毫秒。但看看那个struct tm
。它包含日期所有组成部分的字段。更新:该死,我的错误 - time(3) 确实返回秒。我正在考虑再打一个电话。但无论如何还是要看看 struct tm 的内容。
You're pretty close on. First of all, Tyler's solution will almost work -- you need to use
(24*60*60*1000)
since time(3) returns milliseconds. But have a look at thatstruct tm
. It has fields for all the components of a date.Update: Damn, my mistake -- time(3) does return seconds. I was thinking of another call. But have a look at the contents of
struct tm
anyway.您可以在将
ts
结构体的内容传递给strftime
之前对其进行操作。该月的日期包含在tm_mday
成员中。基本过程:编辑:是的,一个月中的天数从 1 开始编号,而其他所有内容(秒、分钟、小时、工作日和一年中的天数)从 0 开始编号。
You can manipulate the contents of the
ts
struct before passing it tostrftime
. The day of the month is contained in thetm_mday
member. Basic procedure:Edit: Yes, days of the month are numbered from 1 whereas everything else (seconds, minutes, hours, weekdays, and days of the year) are numbered from 0.
也适用于闰秒。
Will work with leap seconds too.