【问题标题】:How do I modify a time_t timestamp in C?如何在 C 中修改 time_t 时间戳?
【发布时间】:2011-05-06 01:25:09
【问题描述】:

这就是我们如何存储当前时间并使用time.h 打印它:

$ cat addt.c
#include<stdio.h>
#include<time.h>

void print_time(time_t tt) {
    char buf[80];
    struct tm* st = localtime(&tt);
    strftime(buf, 80, "%c", st);
    printf("%s\n", buf);
}

int main() {
    time_t t = time(NULL);
    print_time(t);
    return 0;
}
$ gcc addt.c -o addt
$ ./addt
Sat Nov  6 15:55:58 2010
$

如何将例如 5 分 35 秒添加到 time_t t 并将其存储回 t

【问题讨论】:

  • 看看stackoverflow.com/questions/1859201/add-seconds-to-a-date>
  • add seconds to a date的可能重复
  • (严格来说它不是重复的,但考虑到实际提供的答案,它是另一个问题的子集)。

标签: c datetime time


【解决方案1】:

time_t通常是一个整数类型,表示自纪元以来的秒数,因此您应该能够添加 335(5 分 35 秒)。

请记住,ISO C99 标准规定:

clock_ttime_t 中可表示的时间范围和精度是实现定义的。

因此,虽然这通常会起作用(并且在我曾经使用过的每个系统上都如此),但在某些极端情况下可能并非如此。

请参阅以下对您的程序的修改,它增加了 5 分钟(300 秒):

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

void print_time(time_t tt) {
    char buf[80];
    struct tm* st = localtime(&tt);
    strftime(buf, 80, "%c", st);
    printf("%s\n", buf);
}

int main() {
    time_t t = time(NULL);
    print_time(t);
    t += 300;
    print_time(t);
    return 0;
}

输出是:

Sat Nov  6 10:10:34 2010
Sat Nov  6 10:15:34 2010

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2014-10-11
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多