【问题标题】:Getting difference between two dates in number of days?在天数上获得两个日期之间的差异?
【发布时间】:2014-10-07 22:10:16
【问题描述】:

比较两天时,我没有得到正确的日期。在这里,dd=14,mm=8,yy=2014 得到 699 天而不是 730 天

time_t t1, t2;
struct tm my_target_date;

 my_target_date.tm_sec = 0;
 my_target_date.tm_min = 0;
 my_target_date.tm_hour = 0;
 my_target_date.tm_mday = 14;
 my_target_date.tm_mon = 8;
 my_target_date.tm_year = 112; /* Date today */
 t1 = mktime (&my_target_date);
 t2 = time (NULL);
 sprintf (sbuff2,"Number of days since target date : %ld\n", (t2 - t1) / 86400);

【问题讨论】:

  • 除了休息一个月,打电话mktime(&my_target_date);之前,设置my_target_date.tm_isdst。如果不确定夏令时设置,请使用my_target_date.tm_isdst = -1;。其他2个字段tm_wdaytm_yday不需要设置。

标签: c date time


【解决方案1】:

struct tm

int tm_mday; // day of the month — [1, 31]
int tm_mon; // months since January — [0, 11]

tm_mday1 开始,但tm_mon0 开始。因此my_target_date.tm_mon = 8;实际上是九月,你是一个月。

【讨论】:

    【解决方案2】:

    struct tm 结构是-

    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 */
           };
    

    tm结构的成员有:

       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 daylight saving time is in effect, zero if it is
                 not, and negative if the information is not available.
    

    如果输入为dd=14,mm=8,yy=2014,则表示2014年9月14日,因为在tm_mon月份从0开始。所以它会从September 14th 2014 计算天数。所以你在这之间错过了 31 天。

    将您的输入设为dd=14,mm=7,yy=2014

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2013-07-23
      • 2019-05-11
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多