c++时间格式转换

您所在的位置:网站首页 R语言中strptime函数 c++时间格式转换

c++时间格式转换

2024-07-09 22:11| 来源: 网络整理| 查看: 265

openclassroom整理自《linux程序设计》 这两个函数都是时间日期的格式控制函数,在功能上看起来正好相反。strftime将一个tm结构格式化为一个字符串,strptime则是将一个字符串格式化为一个tm结构。

strftime

函数原型:size_t strftime(char *s,size_t maxsize,char *format,const struct tm *timeptr) strftime函数对timeptr指向的tm结构所代表的时间和日期进行格式编排,其结果放在字符串s中。该字符串的长度被设置为(最少)maxsize个字符。格式字符串format用来对写入字符串的字符进行控制,它包含着将被传送到字符串里去的普通字符以及编排时间和日期格式的转换控制符。转换控制符见下表

转换控制符说明%a星期几的简写形式%A星期几的全称%b月份的简写形式%B月份的全称%c日期和时间%d月份中的日期,0-31%H小时,00-23%I12进制小时钟点,01-12%j年份中的日期,001-366%m年份中的月份,01-12%M分,00-59%p上午或下午%S秒,00-60%u星期几,1-7%w星期几,0-6%x当地格式的日期%X当地格式的时间%y年份中的最后两位数,00-99%Y年%Z地理时区名称

具体的控制转换符说明可以查看man.

strptime

函数原型: char *strptime(const char *buf,const char *format,struct tm *timeptr)

format字符串的构建方式和strftime的format字符串完全一样。strptime返回一个指针,指向转换过程处理的最后一个字符后面的那个字符。

看下边一个程序

? View Code C 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 [c] view plain copy print ? #include   #include   #include   #include      int main(){    struct tm *tm_ptr,timestruct;    time_t the_time;    char *buf[256];       (void) time(&the_time);    tm_ptr=localtime(&the_time);    strftime(buf,256,"%A %d %B,%I:%S %p",tm_ptr);    printf("strftime gives: %s/n",buf);       strcpy(buf,"Sat 26 July 2003,17:53 will do fine");       printf("calling strptime with: %s/n",buf);    tm_ptr+×truct;       result=strptime(buf,"%a %d %b %Y,%R",tm_ptr);    printf("strptime consumed up to: %s/n",result);       printf("strptime gives:/n");    printf("date: %02d/%02d/%02d/n",tm_ptr->tm_year%100,tm_ptr->tm_mon+1,tm_ptr->tm_mday);    printf("time: %02d:%02d/n",tm_ptr->tm_hour,tm_ptr->tm_min);    exit(0);  }   #include #include #include #include   int main(){ struct tm *tm_ptr,timestruct; time_t the_time; char *buf[256];   (void) time(&the_time); tm_ptr=localtime(&the_time); strftime(buf,256,"%A %d %B,%I:%S %p",tm_ptr); printf("strftime gives: %s/n",buf);   strcpy(buf,"Sat 26 July 2003,17:53 will do fine");   printf("calling strptime with: %s/n",buf); tm_ptr+×truct;   result=strptime(buf,"%a %d %b %Y,%R",tm_ptr); printf("strptime consumed up to: %s/n",result);   printf("strptime gives:/n"); printf("date: %02d/%02d/%02d/n",tm_ptr->tm_year%100,tm_ptr->tm_mon+1,tm_ptr->tm_mday); printf("time: %02d:%02d/n",tm_ptr->tm_hour,tm_ptr->tm_min); exit(0); }

运行后输出 strftime gives:Sunday 06 June, 11:55 AM calling strptime with:Sat 26 July 2003,17:53 will do fine strptime consumed up to:will do fine strptime gives: date: 03/07/26 time: 17:53



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3