将字符串转化为tm结构体的数据

本文介绍了一种将特定格式的日期时间字符串(如2014-03-2321:41:17)转换为C语言中time结构体的方法。通过使用sscanf函数解析字符串并填充time结构体成员变量。

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

本例中的将要转化的字符串的格式类型为:

    2014-03-23 21:41:17

需转化其他格式类型时更改sscanf()里面的格式控制即可

int string_to_time (char * string, struct tm * time)
{
    int year = 0, month = 0, day = 0, hour = 0, minute = 0, sec = 0;

    memset (time, 0, sizeof (struct tm));
    if(sscanf ((string, "%4d-%2d-%2d %2d:%2d:%2d", 
	        &year, &month, &day, &hour, &minute, &sec) != 6)
    {
        return OPREATE_FAIL;
    }
	
    time->tm_year = year - 1900;
    time->tm_mon = month - 1;
    time->tm_mday = day;
    time->tm_hour = hour;
    time->tm_min = minute;
    time->tm_sec = sec;

    return OPREATE_SUCCESS;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值