2012-03-02 16 views
27

Sto lavorando con l'API REST Azure e stanno usando questo per creare il corpo della richiesta per la conservazione tavolo:Come si costruisce un datetime ISO 8601 in C++?

DateTime.UtcNow.ToString("o") 

che produce:

2012-03-02T04: 07: 34,0,218628 millions Z

si chiama "andata e ritorno" e apparentemente è uno standard ISO (vedi http://en.wikipedia.org/wiki/ISO_8601), ma non ho idea di come replicare dopo aver letto l'articolo wiki.

Qualcuno sa se Boost ha il supporto per questo o forse Qt?

Nota: tornerò da voi dopo il fine settimana dopo averlo confrontato con C#.

risposta

51

Se il tempo al secondo più vicino è abbastanza preciso, è possibile utilizzare strftime:

#include <ctime> 
#include <iostream> 

int main() { 
    time_t now; 
    time(&now); 
    char buf[sizeof "2011-10-08T07:07:09Z"]; 
    strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); 
    // this will work too, if your compiler doesn't support %F or %T: 
    //strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); 
    std::cout << buf << "\n"; 
} 

Se avete bisogno di una maggiore precisione, è possibile utilizzare Boost:

#include <iostream> 
#include <boost/date_time/posix_time/posix_time.hpp> 

int main() { 
    using namespace boost::posix_time; 
    ptime t = microsec_clock::universal_time(); 
    std::cout << to_iso_extended_string(t) << "Z\n"; 
} 
+8

vuoi "% FT% TZ" (ISO 8601 usa la "T" per separare la data dal momento –

3

In Qt, che sarebbe:

QDateTime dt = QDateTime::currentDateTime(); 
dt.setTimeSpec(Qt::UTC); // or Qt::OffsetFromUTC for offset from UTC 
qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate); 
+0

I numeri alla fine è il problema, non la forma alla stringa – chikuba

+0

Intendi la parte frazionaria dei secondi (es. .0218628)? Sono opzionali ... – Koying

+0

come? non è stato possibile vedere nulla nel documento – chikuba

0

Forse in questo modo:

using namespace boost::posix_time; 
ptime t = microsec_clock::universal_time(); 
qDebug() << QString::fromStdString(to_iso_extended_string(t) + "0Z"); // need 7 digits 
1

OK così ho modificato alcune soluzioni che ho trovato, come si avvicinò con la seguente :

static QString getTimeZoneOffset() 
{ 
    QDateTime dt1 = QDateTime::currentDateTime(); 
    QDateTime dt2 = dt1.toUTC(); 
    dt1.setTimeSpec(Qt::UTC); 

int offset = dt2.secsTo(dt1)/3600; 
if (offset >= 0) 
    return QString("%1").arg(offset).rightJustified(2, '0',true).prepend("+"); 
return QString("%1").arg(offset).rightJustified(2, '0',true); 
} 

quindi in formato facilmente una data (aaaa-mM-dd'T'HH: mm: ss.SSSZ):

static QString toISO8601ExtendedFormat(QDateTime date) 
{ 
    QString dateAsString = date.toString(Qt::ISODate); 
    QString timeOffset = Define::getTimeZoneOffset(); 
    qDebug() << "dateAsString :" << dateAsString; 
    qDebug() << "timeOffset :" << timeOffset; 
    timeOffset = QString(".000%1%2").arg(timeOffset).arg("00"); 
    qDebug() << "timeOffset replaced :" << timeOffset; 
    if(dateAsString.contains("Z",Qt::CaseInsensitive)) 
     dateAsString = dateAsString.replace("Z",timeOffset); 
    else 
     dateAsString = dateAsString.append(timeOffset); 
     qDebug() << "dateAsString :" << dateAsString; 
    return dateAsString; 
} 

Per esempio GMT +2 sarebbe simile a questa: 2013-10-14T00: 00: 00,000 + 0200

2

vorrei sottolineare io sono un C++ newb.

Avevo bisogno di una stringa con una data e un'ora ISO 8601 formattate che includevano i millisecondi. Non ho avuto accesso all'aumento.

Questo è più di un hack che una soluzione, ma ha funzionato abbastanza bene per me.

std::string getTime() 
{ 
    timeval curTime; 
    time_t now; 

    time(&now); 
    gettimeofday(&curTime, NULL); 

    int milli = curTime.tv_usec/1000; 
    char buf[sizeof "2011-10-08T07:07:09"]; 
    strftime(buf, sizeof buf, "%FT%T", gmtime(&now)); 
    sprintf(buf, "%s.%dZ", buf, milli); 

    return buf; 
} 

L'output è simile: 2016-04-13T06: 53: 15.485Z

9

Utilizzando la libreria date (C++ 11):

template <class Precision> 
string getISOCurrentTimestamp() 
{ 
    auto now = chrono::system_clock::now(); 
    return date::format("%FT%TZ", date::floor<Precision>(now)); 
} 

Esempio di utilizzo:

cout << getISOCurrentTimestamp<chrono::seconds>(); 
cout << getISOCurrentTimestamp<chrono::milliseconds>(); 
cout << getISOCurrentTimestamp<chrono::microseconds>(); 

uscita:

2017-04-28T15:07:37Z 
2017-04-28T15:07:37.035Z 
2017-04-28T15:07:37.035332Z 
Problemi correlati