c语言,如何进行日期格式转换??

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c语言,如何进行日期格式转换??相关的知识,希望对你有一定的参考价值。

请问如何将日期格式用c语言进行转换,例如:
11/12/2010 转换成 11th Dec 2010
13/12/2010 13rd Dec 2010

1、C里没有相应的库,只能用asctime函数转换成一种固定格式。如果要转换,可以用sprintf把各种数据以“ 1980-01-02 02:03:55 ” 这种标准格式,格式到一个字符串中。

2、asctime函数:
原型:char* asctime (const struct tm * timeptr);
功能:把timeptr指向的tm结构体中储存的时间转换为字符串;
头文件:time.h;
返回值:一个固定格式的字符串。字符串格式为:Www Mmm dd hh:mm:ss yyyy。其中Www为星期,Mmm为月份,dd为日,hh为时,mm为分,ss为秒,yyyy为年份。
3、例程:

#include<time.h>
#include<stdio.h>
int main()
    time_t rawtime;
    struct tm * timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);//使用localtime函数把秒数时间rawtime转换为本地时间以tm结构体保存,并把tm结构体地址储存到timeinfo当中
    printf("当前日期为: %s",asctime(timeinfo));//使用asctime函数把tm结构体中储存的时间转换为字符串,并输出
    return 0;

参考技术A time.h 有函数 strftime 输出各种格式,但没有 你的 11th 13rd 格式。
简单办法是用查表法

#include "stdio.h"
#include "stdlib.h"
void main()

char dmy[20]="13/12/2010";
int i,j;
int a,b,c;
char d[32][5]="0","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th",
"11th","12th","13rd","14th","15th","16th","17th","18th",
"19th",.....,"31st"; // 请自己补全
char m[13][4]=" ","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec";
j = strlen(dmy);
printf("j=%d\n",j);
for (i=0;i<j ;i++) if ( dmy[i] =='/') dmy[i]=' ';
sscanf(dmy,"%d %d %d",&a,&b,&c);
printf("%s %s %d",d[a],m[b],c); // 打印出你要的 13rd Dec 2010

参考技术B c里没有相应的库
但你可以用sprintf把各种数据以“
1980-01-02
02:03:55

这种标准格式,格式到一个字符串中就可以了

以上是关于c语言,如何进行日期格式转换??的主要内容,如果未能解决你的问题,请参考以下文章

c语言将秒数转换为时间格式(24小时制,00:00:00格式)

在EXCEL中如何将日期格式转换,例如把2012/09/01变换成2012-09-01?

如何在 .Net / C# 中将日期转换为 HTTP 格式的日期

如何在Oracle中将时间戳转化为日期格式

将时间戳转化为日期格式

关于在delphi中时间日期的转换问题,高手进