我认为一个丑陋的黑客很有趣:因为您只想确定哪个日期/时间更大,您可以将日期转换为字符串并比较字符串.;-)(好处是你不需要在任何地方都没有的strptime.)
#include <string.h>
#include <time.h>
int main(int argc, char *argv[])
{
const char *str = "2011-03-21 20:25";
char nowbuf[100];
time_t now = time(0);
struct tm *nowtm;
nowtm = localtime(&now);
strftime(nowbuf, sizeof(nowbuf), "%Y-%m-%d %H:%M", nowtm);
if (strncmp(str, nowbuf, strlen(str)) >= 0) puts("future"); else puts("past");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用strptime
从字符串转换为a struct tm
,然后您可以使用mktime
从a转换struct tm
为a time_t
.例如:
// Error checking omitted for expository purposes
const char *timestr = "2011-03-21 20:25";
struct tm t;
strptime(timestr, "%Y-%m-%d %H:%M", &t);
time_t t2 = mktime(&t);
// Now compare t2 with time(NULL) etc.
Run Code Online (Sandbox Code Playgroud)