如何用C更改和格式化日期

时间:2015-06-27 14:44:21

标签: c date datetime

我想使用天数增加日期...例如,如果今天是27.05.2015并且我添加了6天它应该打印3.06.2015

这是我的尝试:

   time_t now;
    struct tm *tm;

    now = time(0);
    if ((tm = localtime (&now)) == NULL) {
        printf ("Error extracting time stuff\n");
        return 1;
    }

    printf ("%02d-%02d-%04d\n", tm->tm_mday + 6, tm->tm_mon, tm->tm_year+1900);

这将胜出:

  

33-05-2015

另外我如何格式化日期:

  

27-JUN-2015

1 个答案:

答案 0 :(得分:1)

像这样你可以

#include <stdio.h>
#include <sys/time.h>
#include <time.h>

int
main(void)
 {
    struct timeval tv;
    char           str[12];
    struct tm     *tm;

    if (gettimeofday(&tv, NULL) == -1)
        return -1; /* error occurred */
    if ((tm = localtime(&tv.tv_sec)) != NULL)
     {
        /* Format as you want */
        strftime(str, sizeof(str), "%d-%b-%Y", tm);
        printf("Today                  : %s\n", str);
     }

    tv.tv_sec += 6 * 24 * 3600; /* add 6 days converted to seconds */
    if ((tm = localtime(&tv.tv_sec)) != NULL)
     {
        /* Format as you want */
        strftime(str, sizeof(str), "%d-%b-%Y", tm);
        printf("After 6 days from today: %s\n", str);
     }

    return 0;
 }