2013-03-06 98 views
0

我有一個格式爲「2012-10-28」的日期表示爲字符串,我想將其轉換爲「28/10/2012」的字符串格式。這可能在C++ MS Visual Studio中使用預定義的函數嗎?在C++中轉換字符串日期時間

+1

你說的是替換所有的「 - 」到「/」你的字串,或者你需要一些時間函數來做到這一點? strptime在Windows中不起作用 – Abhineet 2013-03-06 13:25:14

回答

2

我的工作了這種方式:

Use sscan_f to break date into year, month and day. 
Create struct tm with the data above. 
Use strftime to convert from tm to string with the desired format. 
3

這將做到這一點:

#include <cstdio> 
#include <iostream> 
#include <string> 
using namespace std; 

string format_date(string s) 
{ 
    char buf[11]; 
    int a, b, c; 
    sscanf(s.c_str(), "%d-%d-%d", &a, &b, &c); 
    sprintf(buf, "%02d/%02d/%d", c, b, a); 
    return buf; 
} 

int main() 
{ 
    cout << format_date("2012-09-28") << endl; 
} 
0
在QT(某些嵌入式系統不支持新的計時器類呢,所以這裏) 我這裏

只要給出想法如何轉換一個字符串沒有太多的巨型巨無霸。無論如何,定時器類都具有時代功能。


QString fromSecsSinceEpoch(qint64 epoch) 
{ 
    QTextStream ts; 
    time_t result = epoch;//std::time(NULL); 
    //std::cout << std::asctime(std::localtime(&result)) 
    //   << result << " seconds since the Epoch\n"; 
    ts << asctime(gmtime(&result)); 
    return ts.readAll(); 
} 
qint64 toSecsSinceEpoch(QString sDate)//Mon Nov 25 00:45:23 2013 
{ 
    QHash <QString,int> monthNames; 
    monthNames.insert("Jan",0); 
    monthNames.insert("Feb",1); 
    monthNames.insert("Mar",2); 
    monthNames.insert("Apr",3); 
    monthNames.insert("May",4); 
    monthNames.insert("Jun",5); 
    monthNames.insert("Jul",6); 
    monthNames.insert("Aug",7); 
    monthNames.insert("Sep",8); 
    monthNames.insert("Oct",9); 
    monthNames.insert("Nov",10); 
    monthNames.insert("Dec",11); 


    QStringList l_date = sDate.split(" "); 
    if (l_date.count() != 5) 
    { 
     return 0;//has to be 5 cuz Mon Nov 25 00:45:23 2013 
    } 
    QStringList l_time = l_date[3].split(":"); 
    if (l_time.count() != 3) 
    { 
     return 0;//has to be 3 cuz 00:45:23 
    } 

    struct tm result; 
    result.tm_mday=l_date[2].toInt(); 
    result.tm_mon=monthNames[l_date[1]]; 
    result.tm_year=l_date[4].toInt()-1900;; 

    result.tm_hour=l_time[0].toInt(); 
    result.tm_min=l_time[1].toInt(); 
    result.tm_sec=l_time[2].toInt(); 
    time_t timeEpoch=mktime(&result); 
    qDebug()<<"epochhhh :"<<timeEpoch; 
    return timeEpoch; 
}