繁体   English   中英

比较时间在C

[英]Compare time in C

我正在尝试制作一个在特定日期后打印出消息的程序。 有点像档案馆。 例如,今天只应打印出“ hello”。 第二天,它应该打印出“世界”。 但是它应该仍然打印出“ hello”,因为我已经过了应该已经打印出“ hello”的日期。

我敢肯定,您可以使用一些基本的if条件来执行此操作,并且只需比较localtimed struct tm的值即可,但是我认为有一种更快,更有效的方法。 if条件方法也需要一段很长的代码。 我尝试浏览stackoverflow,发现了difftime方法。 问题是, difftime参数是

double difftime(time_t time1, time_t time0)

而且我不知道如何将本地时间初始化为其中一个,并将特定日期初始化为另一个。

简而言之,我的问题是:

  1. 如何将特定日期设置为time_t变量?

  2. 如何将time_t变量设置为localtime (如果您要使用struct tm localtime = *localtime(&time_t)方法,请告诉我如何将struct变量转换回time_t变量,以便将其插入到difftime的参数)?

缺少的成分是mktime() ,它将struct tm转换回time_t

struct tm then;
then.tm_year = 2015 - 1900;
then.tm_mon  = 5 - 1;
then.tm_mday = 11;
then.tm_hour = 8;
then.tm_min  = 45;
then.tm_sec  = 0;
then.tm_dst  = -1;  // Undefined DST vs standard time

time_t now = mktime(&then);

struct tm *inverse = localtime(&now);

您可以调整结构中的值,然后mktime()将其标准化。 请注意年份和月份的奇怪编码-遥远的过去的遗物。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM