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

来源:互联网 发布:cad线切割编程软件 编辑:程序博客网 时间:2024/06/08 01:01

#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 intint 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 0