我收到格式为“24-9-2016 13:30”的日期结构。现在我想将时间值转换为特定的日期值,我正在计算并且要加减小时数。
所以我不知道:
- 如何使用我拥有的日期值初始化 tm 结构?
- 如何在 tc 结构变量中增加或减少小时数以获得所需的日期?
我的意图是
收到日期“24-9-2016 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
这是关于格式化用户定义的,而不是重复的。
最佳答案
#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(&tm)
来规范化时间结构(例如,将 23:30 添加 5 小时应该得到 04:30(并增加一天),而不是 28:30)。 - 我们使用
strftime
将结果转换回人类可读的形式。
一个可能的问题是这将输出 24-09-2016 18:30
,即它会使用零将月/日数字填充到 2 个位置。如果您不想这样,则必须手动打印/格式化 tm
字段。
关于c - 想要使用 struct tm 执行日期/时间值操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39673816/