如何将字符串转换为日期时间c ++?

时间:2015-09-11 12:10:52

标签: c++ string time

string s = v[2];

        string result = s.substr(s.find_last_of("modify=") + 1, 14);

        cout << result;//output MDTM boost.txt 20150911115551 

我希望转换为YYYY-MM-DD HH:MM

1 个答案:

答案 0 :(得分:0)

要访问与日期和时间相关的函数和结构,您需要在C ++程序中包含头文件。

有四种与时间相关的类型:clock_t,time_t,size_t和tm。类型clock_t,size_t和time_t能够将系统时间和日期表示为某种整数。

结构类型tm以C结构的形式保存日期和时间,具有以下元素:

struct tm {
  int tm_sec;   // seconds of minutes from 0 to 61
  int tm_min;   // minutes of hour from 0 to 59
  int tm_hour;  // hours of day from 0 to 24
  int tm_mday;  // day of month from 1 to 31
  int tm_mon;   // month of year from 0 to 11
  int tm_year;  // year since 1900
  int tm_wday;  // days since sunday
  int tm_yday;  // days since January 1st
  int tm_isdst; // hours of daylight savings time
}

考虑到你有以下格式的数据字符串&#34; YYY-MM-DD HH:MM:SS&#34;,下面的代码显示了如何在日期结构中转换字符串:

#include <iostream>
#include <ctime>
#include <string.h>
#include <cstdlib>

using std::cout;
using std::endl;

int main(int argc, char* argv[])
{
    char date[] = "2012-05-06 21:47:59";
    tm *ltm = new tm;

    char* pch;
    pch = strtok(date, " ,.-:");
    ltm->tm_year = atoi(pch); //get the year value
    ltm->tm_mon = atoi(strtok(NULL, " ,.-:"));  //get the month value
    ltm->tm_mday = atoi(strtok(NULL, " ,.-:")); //get the day value
    ltm->tm_hour = atoi(strtok(NULL, " ,.-:")); //get the hour value
    ltm->tm_min = atoi(strtok(NULL, " ,.-:")); //get the min value
    ltm->tm_sec = atoi(strtok(NULL, " ,.-:")); //get the sec value

    // print various components of tm structure.
    cout << "Year: "<< ltm->tm_year << endl;
    cout << "Month: "<< ltm->tm_mon<< endl;
    cout << "Day: "<< ltm->tm_mday << endl;
    cout << "Time: "<< ltm->tm_hour << ":";
    cout << ltm->tm_min << ":";
    cout << ltm->tm_sec << endl;

    delete ltm;
    return 0;   
}

输出:

Year: 2012
Month: 5
Day: 6
Time: 21:47:59