gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:16:04 26 4
gpt4 key购买 nike

我想使用天数来增加日期...例如,如果今天是 2015 年 5 月 27 日,我添加 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

最佳答案

这样就可以了

#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;
}

关于c - 如何用 C 更改日期和格式化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31089937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com