C++ 将字符串转换成date类型的数据

#include <time.h>       /* time_t, struct tm, time, localtime, strftime */
#include <string>
#include <iostream>
#include <vector>

char* asctime(const struct tm *timeptr){

    static const char mon_name[][4] = {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };
    static char result[13];
    sprintf(result, "%.3s%3d %d\n",
            mon_name[timeptr->tm_mon],
            timeptr->tm_mday,
            1900 + timeptr->tm_year);
    
    return result;
}

//change string to int
int parse_int(const char* str) {
    
	int value = atoi(str);
    
	return value;
}

struct tm* stringToDate(const std::string dateString, const std::string splitstr){
 
    std::string datestr = dateString;

    std::vector<int> yymmdd(3,0);
    

    std::size_t frist = datestr.find(splitstr);
    std::size_t last = datestr.find_last_of(splitstr);
/*
    std::cout <<"year:" << datestr.substr(0, frist) << std::endl;
    std::cout <<"month:" << datestr.substr(frist + 1, last - frist - 1) << std::endl;
    std::cout <<"day:"<< datestr.substr(last + 1, datestr.length()) << std::endl;
    
  */  
    
    time_t rawtime;
    struct tm * timeinfo;

    time (&rawtime);
    timeinfo = localtime (&rawtime);
    
    //将上面取得的数转换成int型数据后 存入vector yymmdd中
    yymmdd[0] = parse_int(datestr.substr(0, frist).c_str());
    yymmdd[1] = parse_int(datestr.substr(frist + 1, last - frist - 1).c_str());
    yymmdd[2] = parse_int(datestr.substr(last + 1, datestr.length()).c_str());
    
    timeinfo->tm_mday = yymmdd[2];
    timeinfo->tm_mon = yymmdd[1] - 1;
    timeinfo->tm_year = yymmdd[0] -1900;
    
    return timeinfo;
}

int main (){
    std::string mystr = "2009-08-15";
    
    printf ("You input date is: %s", asctime(stringToDate(mystr,"-")));
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值