简体   繁体   中英

Compare time in C

I'm trying to make a program that prints out messages after a certain date. Kinda like an archive. For example, today it should only print out "hello". The next day, it should print out "world". But it should still print out "hello" since I've passed the date that "hello" should be printed out already.

I'm sure you can do this with some basic if conditions and just comparing the values inside a localtimed struct tm , but I think there's a faster and more efficient way of doing this. The if condition method takes a ridiculously long code as well. I tried browsing stackoverflow and I found the difftime method. The problem is, the difftime parameters are

double difftime(time_t time1, time_t time0)

and I don't know how to initialize the localtime into one of them and a specific date into the other.

So to cut it short, my questions are:

  1. How do I set a specific date into a time_t variable?

  2. How do I set time_t variable into localtime (if you're going to use the struct tm localtime = *localtime(&time_t) method, would you please tell me how to convert the struct variable back into a time_t variable so I can insert it into the parameters of difftime )?

The missing ingredient is mktime() , which converts a struct tm back to 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);

You can juggle the values in the structure and mktime() will normalize them. Note the wonky encoding of years and months — a relic of the distant past.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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