.ics (iCalender) 文件包含开始和结束时间,如下所示:
DTSTART:20131023T190000
DTEND:20131023T220000
我想使用该信息来构造日期和时间字符串,如下所示:
"September 23, 2013 (Fri)",
"7:00 pm to 10:00 pm"
我环顾了一下时间库,发现 strftime(char *s, size_t max, const char *format, const struct tm *tm)
如果我能弄清楚如何,它可以轻松满足我的需求从我拥有的数据构造最后一个参数。
最佳答案
这是一个粗略且现成的解决方案,可以解决问题。我没有从文件中读取字符串,这听起来像你可以做到的。错误检查也大多被省略,因为它使用硬编码数据。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
void parse_time(char * ics_string, struct tm * dest_tm) {
char year[5], month[3], day[3], hour[3], minute[3], second[3];
sscanf(ics_string, "%4s%2s%2s%*1s%2s%2s%2s",
year, month, day, hour, minute, second);
dest_tm->tm_year = strtol(year, NULL, 10) - 1900;
dest_tm->tm_mon = strtol(month, NULL, 10) - 1;
dest_tm->tm_mday = strtol(day, NULL, 10);
dest_tm->tm_hour = strtol(hour, NULL, 10);
dest_tm->tm_min = strtol(minute, NULL, 10);
dest_tm->tm_sec = strtol(second, NULL, 10);
dest_tm->tm_isdst = -1;
if ( mktime(dest_tm) < 0 ) {
fprintf(stderr, "Couldn't get local time.\n");
exit(EXIT_FAILURE);
}
}
bool same_day(struct tm * first, struct tm * second) {
if ( (first->tm_year == second->tm_year) &&
(first->tm_mon == second->tm_mon) &&
(first->tm_mday == second->tm_mday) ) {
return true;
} else {
return false;
}
}
void calc_diff_string(char * buffer, size_t len,
struct tm * start_tm, struct tm * end_tm) {
char start_buffer[len];
char end_buffer[len];
strftime(start_buffer, len, "%B %d, %Y (%a), %I:%M %p", start_tm);
if ( same_day(start_tm, end_tm) ) {
strftime(end_buffer, len, "%I:%M %p", end_tm);
} else {
strftime(end_buffer, len, "%B %d, %Y (%a), %I:%M %p", end_tm);
}
sprintf(buffer, "%s to %s", start_buffer, end_buffer);
}
void print_time_diff(char * start_time, char * end_time) {
struct tm start_tm, end_tm;
char buffer[1024];
parse_time(start_time, &start_tm);
parse_time(end_time, &end_tm);
calc_diff_string(buffer, sizeof(buffer), &start_tm, &end_tm);
puts(buffer);
}
int main(void) {
print_time_diff("20131023T190000", "20131023T220000");
print_time_diff("20131023T190000", "20131024T220000");
return EXIT_SUCCESS;
}
输出:
paul@local:~/src/c/scratch/timestrip$ ./timestrip
October 23, 2013 (Wed), 07:00 PM to 10:00 PM
October 23, 2013 (Wed), 07:00 PM to October 24, 2013 (Thu), 10:00 PM
paul@local:~/src/c/scratch/timestrip$
简要评论:
parse_time()
接受您的格式的字符串(不包括DTSTART:
和DTEND:
前缀)并填充struct tm
与相应的时间。same_day()
如果两个时间在同一天,则返回true
,因此您会在输出中看到简短的消息。calc_diff_string()
计算您的输出字符串。print_time_diff()
将它们全部粘合在一起并输出您的字符串。
关于c - 使用 time.h,我可以根据 .ics 文件中的时间构造日期和时间字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19237723/