简体   繁体   English

如何在C ++中将字符串日期与time_t进行比较?

[英]How to compare string date with time_t in c++?

I have string below. 我下面有字符串。

std::string _valid = "2014-03-28 16:45:59";

int y1, M1, d1, h1, m1, s1;
sscanf_s(_valid.c_str(), "%d-%d-%d %d:%d:%d", &y1, &M1, &d1, &h1, &m1, &s1);

Now, I can get year, month, day and so on... 现在,我可以获得年,月,日等等。

Now, I have to determine whether that time is earlier than current datetime. 现在,我必须确定该时间是否早于当前日期时间。

time_t now  = time(NULL);

But, time_t always returns me the time in unix timestamp. 但是,time_t总是以unix时间戳返回我的时间。

How can I compare the date? 如何比较日期?

Set to struct tm , then generate time_t by function mktime . 设置为struct tm ,然后通过函数mktime生成time_t You can compare the value of two time_t directly. 您可以直接比较两个time_t的值。

You can also use SYSTEMTIME and FILETIME from windows.h. 您也可以从windows.h使用SYSTEMTIMEFILETIME Set to SYSTEMTIME then generate FILETIME by function SystemTimeToFileTime . 设置为SYSTEMTIME,然后通过SystemTimeToFileTime函数生成FILETIME。 Compare two FILETIME by function CompareFileTime . 通过功能CompareFileTime比较两个FILETIME。 To compute the distance between two FILETIME, I'm writing the follow ugly code: 为了计算两个FILETIME之间的距离,我正在编写以下丑陋的代码:

__int64 duration = ((*(__int64 *)&ft2) - (*(__int64 *)&ft1));

Note that SYSTEMTIME has higher resolution than struct tm. 请注意,SYSTEMTIME比struct tm具有更高的分辨率。

I think you are looking for the mktime function. 我认为您正在寻找mktime函数。 The details are here http://linux.die.net/man/3/mktime , but in a nutshell... 详细信息在这里http://linux.die.net/man/3/mktime ,但总的来说...

#include <time.h>
time_t mktime(struct tm *tm);

where the struct tm is defined in time.h as... 在t.h中将struct tm定义为...

struct tm
{
  int tm_sec;           /* Seconds. [0-60] (1 leap second) */
  int tm_min;           /* Minutes. [0-59] */
  int tm_hour;          /* Hours.   [0-23] */
  int tm_mday;          /* Day.     [1-31] */
  int tm_mon;           /* Month.   [0-11] */
  int tm_year;          /* Year - 1900.  */
  int tm_wday;          /* Day of week. [0-6] */
  int tm_yday;          /* Days in year.[0-365] */
  int tm_isdst;         /* DST.     [-1/0/1]*/

#ifdef  __USE_BSD
  long int tm_gmtoff;       /* Seconds east of UTC.  */
  __const char *tm_zone;    /* Timezone abbreviation.  */
#else
  long int __tm_gmtoff;     /* Seconds east of UTC.  */
  __const char *__tm_zone;  /* Timezone abbreviation.  */
#endif
};

Hope this helps. 希望这可以帮助。

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

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