我收到“24-9-2016 13:30”格式的日期结构。现在我想将时间值转换为特定的日期值,我正在进行计算,并且需要加上或减去的小时数。
所以我不知道:
我的意图是
收到日期“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
这是关于格式化用户定义的不重复。
答案 0 :(得分:2)
#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
来解析输入字符串。tm_hour += 5
一样简单。tm_isdst
设置为-1
,告诉mktime
自动确定夏令时是否应该生效。mktime(&tm)
来规范化时间结构(例如,在04:30增加5小时至23:30(并且增加一天),而不是28:30)。strftime
将结果转换回人类可读的形式。可能的问题是,这将输出24-09-2016 18:30
,即它会使用零将月/日数字填充到2个位置。如果您不想这样,则必须手动打印/格式化tm
字段。