时间与字符串相互转化

本文详细介绍了如何使用strptime和strftime函数实现时间字符串与struct tm结构之间的相互转换,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用strptime、strftime进行时间字符串与时间结构struct tm之间的转换

           struct tm {
               int tm_sec;    /* Seconds (0-60) */
               int tm_min;    /* Minutes (0-59) */
               int tm_hour;   /* Hours (0-23) */
               int tm_mday;   /* Day of the month (1-31) */
               int tm_mon;    /* Month (0-11) */
               int tm_year;   /* Year - 1900 */
               int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
               int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
               int tm_isdst;  /* Daylight saving time */
           };

头文件:

#include <time.h>


---将时间字符串转换为tm

char *strptime(const char *s, const char *format, struct tm *tm);

s:时间字符串,如:2017-10-20 12:32   、  17:23

format:时间格式

tm:struct tm结构

return: NULL表示转换失败


---将tm转化为时间字符串

size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

s:结果缓存

max:最大长度限制

format:转化格式

tm:tm结构

return:0    error


(备注:若编译是出现如下错误:

changetime.c: In function ‘main’:
changetime.c:16:12: warning: implicit declaration of function ‘strptime’ [-Wimplicit-function-declaration]
  if( ( p = strptime("2017-05-23 5:32:12", "%Y-%m-%d %H:%M:%S", &tim) ) != NULL ) {
            ^
changetime.c:16:10: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
  if( ( p = strptime("2017-05-23 5:32:12", "%Y-%m-%d %H:%M:%S", &tim) ) != NULL ) {
        
在编译选项上加上-D_GNU_SOURCE -D__USE_XOPEN即可)

例:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int
main(void)
{
        struct tm tim;
        char *p = NULL;
        char buf[100];
        int size;

        memset(&tim, 0, sizeof(struct tm));
        if( ( p = strptime("2017-05-23 5:32:12", "%Y-%m-%d %H:%M:%S", &tim) ) != NULL ) {
                printf("year:%d\n", tim.tm_year + 1900);
                printf("month:%d\n", tim.tm_mon + 1);
                printf("day:%d\n", tim.tm_mday);
                printf("hour:%d\n", tim.tm_hour);
                printf("minute:%d\n", tim.tm_min);
                printf("second:%d\n", tim.tm_sec);
        } else {
                printf("strptime error!\n");
        }

        if( strftime(buf, sizeof(buf) - 1, "%Y-%m-%d %H:%M:%S", &tim) != 0 ) {
                printf("time:%s\n", buf);
        } else {
                printf("strftime error!\n");
        }

        return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stone8761

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值