其实这个问题很简单,就是获取本地时间,然后将整型时间变量转换为字符串型,但就这个问题就搞了我一个多小时,郁闷的是最后证明自己写的代码还不好用,而这个问题只要一个命令即可搞定,哎!不说了,在此贴出来,以此为鉴。
点击(此处)折叠或打开
-
#include<stdio.h>
-
#include<time.h>
-
#include<math.h>
-
typedef struct _tag_stm{
-
char syear[5] ;
-
char smon[5] ;
-
char sday[5] ;
-
char shour[5] ;
-
char smin[5] ;
-
char ssec[5] ;
-
}stm_t;
-
-
int Get_Tm_Str(struct tm *tm, stm_t *tm_str)
-
{
-
int i = 0 ,j = 0;
-
(tm->tm_year) += 2000 ;
-
-
-
for(i = 0; i < 5; i++)
-
{
-
if((tm->tm_year / 10) > 0)
-
{
-
tm_str->syear[i] = tm->tm_year / (10000/(pow(10,i+1))) + '0';
-
tm->tm_year %= 10000/(pow(10,i+1));
-
}
-
else if(((tm->tm_year / 10) == 0) && tm->tm_year > 0){
-
tm_str->syear[i] = tm->tm_year + '0';
-
tm_str->syear[i + 1] = '\0';
-
tm->tm_year = 0;
-
}
-
if((tm->tm_mon / 10) > 0)
-
{
-
tm_str->smon[i] = tm->tm_mon / (100/(pow(10,i+1))) + '0';
-
tm->tm_mon %= 100/(pow(10,i+1));
-
}
-
else if(((tm->tm_mon / 10) == 0) && tm->tm_mon > 0){
-
tm_str->smon[i] = tm->tm_mon + '0';
-
tm_str->smon[i + 1] = '\0';
-
tm->tm_mon = 0;
-
}
-
if((tm->tm_mday / 10) > 0)
-
{
-
tm_str->sday[i] = tm->tm_mday / (100/(pow(10,i+1))) + '0';
-
tm->tm_mday %= 100/(pow(10,i+1));
-
}
-
else if(((tm->tm_mday / 10) == 0) && tm->tm_mday > 0){
-
tm_str->sday[i] = tm->tm_mday + '0';
-
tm_str->sday[i + 1] = '\0';
-
tm->tm_mday = 0;
-
}
-
}
-
return 0;
-
}
-
int main(void)
-
{
-
stm_t tm_str;
-
struct tm *tm;
-
time_t now;
-
now = time(NULL);
-
tm = localtime(&now);
-
-
Get_Tm_Str(tm, &tm_str);
-
//
-
printf("the tm_str->s_year %s",tm_str.syear);
-
printf("the tm_str->s_mon %s",tm_str.smon);
-
printf("the tm_str->s_day %s",tm_str.sday);
-
-
while(1);
- }
点击(此处)折叠或打开
-
typedef struct _tag_stm{
-
char syear[5] ;
-
char smon[3] ;
-
char sday[3] ;
-
char shour[3] ;
-
char smin[3] ;
-
char ssec[3] ;
-
}stm_t;
-
-
int Get_Tm_Str(struct tm *tm, stm_t *tm_str)
-
{
-
tm->tm_year += 1900;
-
do{
-
sprintf(tm_str->syear, "%4d", tm->tm_year);
-
sprintf(tm_str->smon, "%2d", tm->tm_mon);
-
sprintf(tm_str->sday, "%2d", tm->tm_mday);
-
sprintf(tm_str->shour, "%2d", tm->tm_hour);
-
sprintf(tm_str->smin, "%2d", tm->tm_min);
-
sprintf(tm_str->ssec, "%2d", tm->tm_sec);
-
}while(0);
-
return 0;
-
-
- }