【问题标题】:Get milliseconds difference from time and date string values in C获取 C 中时间和日期字符串值的毫秒差
【发布时间】:2016-02-29 17:27:59
【问题描述】:

我在变量中有两个日期和时间字符串。我需要以毫秒为单位计算这两个日期和时间值之间的差异。如何在 C 中获得它。该解决方案应该跨平台工作(至少是 windows 和 unix)。

char date1[] = {"26/11/2015"};
char time1[] = {"20:22:19"};
char date2[] = {"26/11/2015"};
char time2[] = {"20:23:19"};

首先,我需要将其保存到某个时间结构中,然后比较 2 个时间结构以获得差异。 C 库中可用于执行此操作的时间结构是什么。

【问题讨论】:

  • 请注意:您不需要库来执行此操作。你可以做一些简单的数学。其次,要获得毫秒,您只需在时间中添加 3 个零,因为它们一开始就不是毫秒精度。
  • 您的日期和时间必须采用这种格式吗?如果您可以在type time_t 中获得它,那将为您节省大量工作。
  • @Jite 不同意“做一些简单的数学运算”。有效年份的范围是多少?是否只提交有效日期?代码应该考虑夏令时吗?闰年规则,更容易拨打mktime()

标签: c time c-libraries


【解决方案1】:

使用mktime()difftime()

mktime 函数返回编码为time_t 类型值的指定日历时间。如果无法表示日历时间,则该函数返回值(time_t)(-1)。 C11dr §7.27.2.3 4

difftime 函数返回以秒为单位的差值作为double §7.27.2.2 2

#include <time.h>
#include <stdlib.h>
#include <string.h>

time_t parse_dt(const char *mdy, const char *hms) {
  struct tm tm;
  memset(&tm, 0, sizeof tm);
  if (3 != sscanf(mdy, "%d/%d/%d", &tm.tm_mon, &tm.tm_mday, &tm.tm_year)) return -1;
  tm.tm_year -= 1900;
  tm.tm_mday++;
  if (3 != sscanf(hms, "%d:%d:%d", &tm.tm_hour, &tm.tm_min, &tm.tm_sec)) return -1;
  tm.tm_isdst = -1;  // Assume local time
  return mktime(&tm);
}

int main() {
  // application
  char date1[] = { "26/11/2015" };
  char time1[] = { "20:22:19" };
  char date2[] = { "26/11/2015" };
  char time2[] = { "20:23:19" };
  time_t t1 = parse_dt(date1, time1);
  time_t t2 = parse_dt(date2, time2);
  if (t1 == -1 || t2 == -1) return 1;
  printf("Time difference %.3f\n", difftime(t2, t1) * 1000.0);
  return 0;
}

输出

Time difference 60000.000

【讨论】:

    【解决方案2】:

    来自 mktime() 的手册页

    这是 mktime() 的原型

    time_t mktime(struct tm *tm);
    

    这是函数mktime()的描述

      The mktime() function takes an argument representing
       broken-down time which is a representation separated into year,  month,
       day, and so on.
    
       Broken-down  time  is  stored  in  the structure tm which is defined in
       <time.h> as follows:
    
           struct tm {
               int tm_sec;         /* seconds */
               int tm_min;         /* minutes */
               int tm_hour;        /* hours */
               int tm_mday;        /* day of the month */
               int tm_mon;         /* month */
               int tm_year;        /* year */
               int tm_wday;        /* day of the week */
               int tm_yday;        /* day in the year */
               int tm_isdst;       /* daylight saving time */
           };
    
       The members of the tm structure are:
    
       tm_sec    The number of seconds after the minute, normally in the range
                 0 to 59, but can be up to 60 to allow for leap seconds.
    
       tm_min    The number of minutes after the hour, in the range 0 to 59.
    
       tm_hour   The number of hours past midnight, in the range 0 to 23.
    
       tm_mday   The day of the month, in the range 1 to 31.
    
       tm_mon    The number of months since January, in the range 0 to 11.
    
       tm_year   The number of years since 1900.
    
       tm_wday   The number of days since Sunday, in the range 0 to 6.
    
       tm_yday   The number of days since January 1, in the range 0 to 365.
    
       tm_isdst  A  flag  that  indicates  whether  daylight saving time is in
                 effect at the time described.  The value is positive if  day‐
                 light  saving time is in effect, zero if it is not, and nega‐
                 tive if the information is not available.
    
    
       The  mktime() function converts a broken-down time structure, expressed
       as local time, to calendar time representation.  The  function  ignores
       the  values  supplied  by the caller in the tm_wday and tm_yday fields.
       The value specified in the tm_isdst field informs mktime()  whether  or
       not  daylight  saving  time (DST) is in effect for the time supplied in
       the tm structure: a positive value means DST is in effect;  zero  means
       that  DST  is  not  in effect; and a negative value means that mktime()
       should (use timezone information and system databases  to)  attempt  to
       determine whether DST is in effect at the specified time.
    
       The  mktime()  function modifies the fields of the tm structure as fol‐
       lows: tm_wday and tm_yday are set to values determined  from  the  con‐
       tents of the other fields; if structure members are outside their valid
       interval, they will be normalized (so that, for example, 40 October  is
       changed  into  9  November); tm_isdst is set (regardless of its initial
       value) to a positive value or to 0, respectively, to  indicate  whether
       DST  is  or  is  not in effect at the specified time.  Calling mktime()
       also sets the external variable tzname with information about the  cur‐
       rent timezone.
    
       If  the  specified  broken-down  time cannot be represented as calendar
       time (seconds since the Epoch), mktime() returns (time_t) -1  and  does
       not alter the members of the broken-down time structure.
    

    ============================================

    这是来自difftime() 的手册页

    这是原型:

    double difftime(time_t time1, time_t time0);
    

    这是描述:

       The  difftime()  function returns the number of seconds elapsed between
       time time1 and time time0, represented as a double.  Each of the  times
       is  specified  in calendar time, which means its value is a measurement
       (in seconds) relative to the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
    

    在几秒钟内得到结果。要以毫秒为单位获得结果,请乘以 1000.0

    【讨论】:

    • 使用上面的信息,解析字符串,从0调整月份的偏移量等设置tm结构中的字段,调用mktime()。对两组数据执行此操作。然后调用difftime() 得到以秒为单位的差异(作为双精度值),将差异乘以 1000.0 得到毫秒
    • 这些函数是标准“c”库的一部分,因此在 windows 中可用。为什么要问它是否可以在Windows中工作。只需编写代码,编译它,然后运行它。这将使您能够了解更多信息并证明它可以在 Windows 中运行。 (请注意,标准的“c”库与 MSDN 库不同,也与 windows.h 头文件中的内容不同
    猜你喜欢
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2018-12-22
    • 2017-02-14
    • 2022-11-23
    相关资源
    最近更新 更多