使用ctime将给定日期推进到下一个日历日期的问题 [英] Issue with using ctime to advance a given date to next calendar date

查看:177
本文介绍了使用ctime将给定日期推进到下一个日历日期的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码段,将输入日期推进到以下日历日期。在用g ++ 4.1.2编译的虚拟源文件中测试时,这很好。

I wrote the following piece of code to advance the input date to the following calendar date. This works well when tested in a dummy source file compiled with g++ 4.1.2

但是,当从公司的模拟器运行下面的代码对我这一点),它打破了20021027;即除20021027以外的日期,它的工作原理如下,但20021027,它返回20021027本身。

However, when running the following code from within my firm's simulator(intricate details of which are unavailable to me at this point), it breaks on 20021027; i.e. for dates other than 20021027, it works as intended but for 20021027, it returns 20021027 itself.

请告诉我们可能会出错?

Please advise as to what could be going wrong?

int nextday(const int &date, int n=1)
{
    struct tm curr_time;

    int yyyy = curr_time.tm_year = date/10000-1900;
    int mm = curr_time.tm_mon=(date/100)%100-1;
    int dd = curr_time.tm_mday=date%100;
    curr_time.tm_min=0;
    curr_time.tm_sec=0;
    curr_time.tm_hour=0;

    time_t next = mktime(&curr_time) + 24*60*60*n;
    struct tm new_time;
    localtime_r(&next,&new_time);
    yyyy = 1900 + new_time.tm_year;
    mm = 1 + new_time.tm_mon;
    dd = new_time.tm_mday;
    return (10000*yyyy+100*mm+dd);
}


推荐答案

一个日期会导致问题,但我不是
明白你为什么要做的事情的艰难的方式。在调用 mktime 之前,只需向
tm_mday 字段添加一个,然后提取更正的
值从 struct tm 中传入 mktime 。 (有一个原因
为什么指针 mktime 指向非const。)像:

I don't see why that one date would cause problems, but I don't understand why you're doing things the hard way. Just add one to the tm_mday field before calling mktime, then extract the corrected values from the struct tm you passed into mktime. (There's a reason why the pointer into mktime points to non-const.) Something like:

int
nextday( int date, int n = 1 )
{
    tm broken_down;
    broken_down.tm_year = date / 10000 - 1900;
    broken_down.tm_mon = (date / 100) % 100 - 1;
    broken_down.tm_mday = date % 100 + n;
    broken_down.tm_hour = 12;  // avoid issues with summer time, etc.
    broken_down.tm_min = 0;
    broken_down.tm_sec = 0;
    mktime( &broken_down );
    return (broken_down.tm_year + 1900) * 10000
        +  (broken_down.tm_mon + 1) * 100
        +  broken_down.tm_mday;
}

(您可能需要添加一些健全性检查, c $ c> int
传入的确实代表了一个预期格式的日期,而
n 一些合理的范围,或者如果你可以影响决定,
使用一些标准的日期格式,所以你不必。)

(You might want to add some sanity checks, i.e. verify that the int passed in really does represent a date in the expected format, and that n is in some reasonable range. Or if you can influence the decision, use some standard date format, so you don't have to.)

d怀疑模拟器中的一些问题,特别是如果它在本地使用相同的值。

Anyway, I'd suspect some problem in the simulator, especially if it works with the same value locally.

这篇关于使用ctime将给定日期推进到下一个日历日期的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆