【问题标题】:Want to perform date/time value manipulation using struct tm想要使用 struct tm 执行日期/时间值操作
【发布时间】:2017-02-02 02:01:09
【问题描述】:

我收到“24-9-2016 13:30”格式的日期结构。现在我想将时间值转换为特定的日期值,我正在计算并且需要添加或减去的小时数。

所以我不知道:

  • 如何使用我拥有的日期值初始化 tm 结构?
  • 如何在 tc struct 变量中添加或减去小时以获取所需的日期?

我的意图是
收到日期“2016 年 9 月 24 日 13:30”和 5 小时添加
所以最终日期:“24-9-2016 18:30”

//Temporarily init time to local

time_t tempTime
time(&tempTime);
struct tm *initStruct = localtime(&tempTime);//initialize it with local time
//now modify it to user defined date
initStruct ->tm_year = 2016;
initStruct->tm_mon = 9;
initStruct->tm_hour = 13;
.
.
.
 //Not sure how can I subtract or add hours in this struct to get desired date value

这是关于格式化用户定义而不是重复。

【问题讨论】:

  • 如果你想要一个工业级的解决方案,这里是:userguide.icu-project.org/datetime/timezone/examples - libicu 是 C 中在任意时区之间转换时间的标准方法。
  • 不是真的,日期来自用户,需要执行额外的步骤,主要是如何在 struct tm 中添加或减去。
  • 你需要的时区是系统时区,还是用户任意选择的时区?
  • 详细计算已经到位,它给出了在用户给定日期应该添加/减去多少小时。我不确定如何在 struct tm 中应用这些值。

标签: c date datetime time


【解决方案1】:
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    struct tm tm = {0};
    if (!strptime("24-9-2016 13:30", "%d-%m-%Y %H:%M", &tm)) {
        return EXIT_FAILURE;
    }

    tm.tm_hour += 5;
    tm.tm_isdst = -1;
    mktime(&tm);

    char buf[40];
    if (!strftime(buf, sizeof buf, "%d-%m-%Y %H:%M", &tm)) {
        return EXIT_FAILURE;
    }

    printf("result: %s\n", buf);
    return EXIT_SUCCESS;
}

注意事项:

  • 我们将tm初始化为全零,然后使用strptime解析输入字符串。
  • 增加 5 小时就像 tm_hour += 5 一样简单。
  • 我们将tm_isdst 设置为-1 以告诉mktime 自动确定夏令时是否应该生效。
  • 之后我们调用mktime(&amp;tm) 来规范时间结构(例如,将 5 小时添加到 23:30 应该会导致 04:30(并增加一天),而不是 28:30)。
  • 我们使用strftime 将结果转换回人类可读的形式。

一个可能的问题是这将输出24-09-2016 18:30,即它将使用零将月/日数字填充到两个位置。如果您不想这样做,则必须手动打印/格式化 tm 字段。

【讨论】:

  • 是的,这就是我想做的事情。谢谢@melpomene。一件事是,我的代码将在 solaris 中运行,我认为 strptime() 在那里不可用。那里有其他选择吗?或者我将不得不为 strptime 中所做的事情编写自己的代码?
  • @user987316 根据docs.oracle.com/cd/E23824_01/html/821-1465/…strptime 可用。
  • 如果我必须添加小时值,例如 4.5,我该怎么做? tm_hour 是整数。
  • @user987316 将 4 添加到 tm_hour 并将 30 添加到 tm_min
  • @user987316 将 4 添加到 tm_hour 和 30 到 tm_min 1) 将 4*60+30 添加到 tm_min 或 2) 将 (4*60+30)*60 添加到tm_secmktime() 将根据需要调整字段。
猜你喜欢
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2012-05-14
  • 2012-12-21
相关资源
最近更新 更多