为日期添加秒数

Vij*_*jay 13 c unix datetime

我需要在日期中添加秒数.例如,如果我有一个日期,例如2009127000000,我需要将秒添加到此日期.另一个例子,加上50秒到20091231235957.

这可能在C?

Mic*_*urr 31

在POSIX中,time_t值被指定为秒,但是C标准不能保证这一点,因此在非POSIX系统上可能不是这样.它通常是(事实上,我不确定它不是一个代表秒数的值).

下面是一个time_t使用标准库工具添加时间值的示例,该时间值不假设表示秒数,这对于操作时间来说真的不是特别好:

#include <time.h>
#include <stdio.h>

int main()
{
    time_t now = time( NULL);

    struct tm now_tm = *localtime( &now);


    struct tm then_tm = now_tm;
    then_tm.tm_sec += 50;   // add 50 seconds to the time

    mktime( &then_tm);      // normalize it

    printf( "%s\n", asctime( &now_tm));
    printf( "%s\n", asctime( &then_tm));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

将时间字符串解析为适当的struct tm变量留作练习.该strftime()函数可用于格式化一个新strptime()函数(POSIX 函数可以帮助解析).

  • @Lazer:`mktime`返回你想要的`time_t`. (2认同)

小智 7

C日期/时间类型time_t实现为自特定日期以来的秒数,因此要向其添加秒数,您只需使用常规算术.如果这不是您要问的问题,请让您的问题更清楚.

  • `time_t`通常是秒,但不一定如此. (21认同)

pmg*_*pmg 7

使用来自的类型和功能<time.h>.

time_t now = time(0);
time_t now_plus_50_seconds = now + 50;
time_t now_plus_2_hours = now + 7200;
Run Code Online (Sandbox Code Playgroud)

<time.h>声明处理time_tstruct tm类型的函数.这些功能可以做你想做的一切.