加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在c中构建日期字符串

发布时间:2020-12-16 10:43:29 所属栏目:百科 来源:网络整理
导读:我目前正在研究一个c项目,我正在尝试从系统中获取日期并将其构建为字符串. 我对c很新,所以我现在正在学习,但是我无法让它工作.以下是我的代码 time_t now = time(NULL);struct tm *t = localtime(now);char currentDate[13];char day[3];char month[3];char
我目前正在研究一个c项目,我正在尝试从系统中获取日期并将其构建为字符串.

我对c很新,所以我现在正在学习,但是我无法让它工作.以下是我的代码

time_t now = time(NULL);
struct tm *t = localtime(&now);
char currentDate[13];
char day[3];
char month[3];
char year[5];
char hour[3];
char min[3];
sprintf(day,"%02d",t->tm_mday,sizeof(day));
sprintf(month,t->tm_mon+1,sizeof(month));
sprintf(year,"%04d",t->tm_year + 1900,sizeof(year));
sprintf(hour,t->tm_hour,sizeof(hour));
sprintf(min,t->tm_min,sizeof(min));
strcat(currentDate,day);
strcat(currentDate,month);
strcat(currentDate,year);
strcat(currentDate,hour);
strcat(currentDate,min);
printf("Current Date: %s",currentDate);

当它打印时,它只会打印出一堆垃圾,例如垃圾.

Current Date: ??x?·Z?¤???·???????′????·^X????<95>?o???·^F^F?^P^_

我究竟做错了什么.

解决方法

我会考虑使用 ctime和/或 strftime.它可能会让你得到你想要的东西,而不会过多地使用字符串和时间字段.

使用strftime:

char text[100];
time_t now = time(NULL);
struct tm *t = localtime(&now);


strftime(text,sizeof(text)-1,"%d %m %Y %H:%M",t);
printf("Current Date: %s",text);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读