如何在 C 语言中从系统时间打印未来时间.例如,如果现在是上午 10 点,则改为打印上午 12 点



我目前正在学习C编程,我正在尝试为模拟机场的下一次预定航班安排一个时间。 我虽然我可以使用系统时间,然后将其修改,以便从那一刻起放置 3 小时的时间。但是,我只能找到将当前时间放在系统上的解决方案。任何帮助将不胜感激。

我已经尝试了几种不同的方法,我见过其他人这样做,但到目前为止还没有成功修改它们。我对 C 编程仍然很陌生,所以我无法阅读其中的许多函数,因此找不到在其中编辑或更改的位置以达到预期的结果。

#include<stdio.h>
#include<time.h>
int main(){
time_t t;
time(&t);
printf("n right now the time is: %s",ctime(&t));
}

这将输出到"2019 年 8 月 12 日星期一 10:00:17" 如果当前时间是上午 10 点,我的最终目标是类似于"下午 12:00">

t

存储自 unix 纪元 (1970-01-01 00:00 UTC( 以来的秒数。 因此,您可以简单地向其添加3h = 3600*3 = 10800

time_t t;
time(&t);
t += 10800;
printf("n In 3 hours the time is: %s",ctime(&t));

由于航班每 3 小时一班,因此我认为be modified so it out puts which ever time is 3 hours from that moment.是指从当前时刻起最多 3 小时。

1(避免做出不可移植的假设,即time_t以秒为单位。

2(转换为本地时间,对.tm_hour成员进行数学运算。

time_t t;
if (time(&t) == -1) Handle_invalid_time();
printf("Right now the time is: %s",ctime(&t));
struct tm *tm = localtime(&t);
if (tm == NULL) Handle_invalid_conversion();
tm->tm_hour += 3;
tm->tm_min = 0;
tm->tm_sec = 0;
// re-adjust members to their usual range  (Handle going into next, day, month, year)
mktime(tm);
printf("Flight time: %s", asctime(tm));

最新更新