给一个日期加上秒数

18

我需要在日期中添加秒数。 例如,如果我有一个日期,如2009127000000,则需要将秒数添加到此日期中。 另一个例子是,在20091231235957的基础上再增加50秒。

这在C语言中是否可行?


我认为你的示例中日期格式不够明确。2009127000000 可能是12月7日或1月27日。 - Thomas
@benjamin,请阅读ctime(日期/时间转换函数)和strptime(将时间的字符串表示转换为时间tm结构)的man页面。 - Glen
4个回答

41
在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;
}

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


1
如何从修改后的“then_tm”中获取一个“time_t”? - Lazer
2
@Lazer:mktime函数返回你所需的time_t时间类型。 - Steve Jessop
1
@Michael Burr。只有当秒数小于60时,这才是正确的。否则,您必须自己进行整个计算。 - abhi
@abhi 为什么?它可以使用任何你想要的秒数:50、200、3600、86400等。显然用户会知道3600秒是多少时间。 - cesargastonec
1
不好意思,秒和分钟需要自己管理。将120添加到 tm_min 会得到类似于 当前时间:19:56:21 将在19:176:21触发 的结果,使用 std::put_time(my_tm,"%X") - Vassilis

12

使用<time.h>中的类型和函数。

time_t now = time(0);
time_t now_plus_50_seconds = now + 50;
time_t now_plus_2_hours = now + 7200;

<time.h> 声明了处理 time_tstruct tm 类型的函数,这些函数可以满足你的所有需求。


应该是答案。清晰明了,有很好的例子。+1 - MyDaftQuestions
更新自POSIX 2016的<time.h>:http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html - pmg
这是通用答案,其他答案并不能很好地解决问题。 - Meric Ozcan
1
如果time_t不是以整秒表示的(并非所有平台都保证),则此方法无效。 - TimeS

8

C 语言的日期/时间类型 time_t 是从某个特定日期开始计算的秒数,因此要向其中添加秒数,只需使用普通算术即可。如果这不是您所询问的,请明确您的问题。


26
time_t 通常表示秒数,但不一定如此。 - Michael Burr
请注意,这个答案并不总是正确的。请参考@MichaelBurr的答案:https://dev59.com/vHI-5IYBdhLWcg3wbXtN#1860996 - Han

1
尝试像这样做:(注意:没有错误检查)
include <time.h>

char* string = ...;
char  buf[80];
struct tm;
strptime(string, "%Y%m...", &tm);
tm->tm_isdst = 0;
strftime(buf, sizeof(buf), "%Y%m...", localtime(mktime(&tm) + 50));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接