0

.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)如果我能弄清楚如何从我拥有的数据中构造最后一个参数,那么它可以很容易地满足我的需求。

4

1 回答 1

1

这是一个粗略且现成的解决方案,可以解决问题。我没有从文件中读取字符串,这听起来像是你可以做到的。错误检查也大多被忽略了,因为它使用硬编码数据。

#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:and前缀)并用相应的时间DTEND:填充 a 。struct tm
  • same_day()true如果两个时间在同一天,则返回,因此您会在输出中获得简短消息。
  • calc_diff_string()计算你的输出字符串。
  • print_time_diff()将它们粘合在一起并输出您的字符串。
于 2013-10-08T02:35:25.253 回答