C'è un modo multipiattaforma per ottenere la data e l'ora attuali in C++?
Il C++ condivide le sue funzioni data/ora con il C. La struttura tm è probabilmente la più facile da usare per un programmatore C++ - la seguente stampa la data di oggi:
#include <ctime>
#include <iostream>
int main() {
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< "\n";
}
Le librerie std C forniscono time()
.
Si tratta di secondi dall'epoca e può essere convertito in data e H:M:S
usando funzioni C standard. Boost ha anche una libreria tempo/data che puoi controllare.
time_t timev;
time(&timev);
la libreria standard C++ non fornisce un tipo di data adeguato. Il C++ eredita le strutture e le funzioni per la manipolazione di data e ora dal C, insieme a un paio di funzioni di input e output di data/ora che tengono conto della localizzazione.
// Current date/time based on current system
time_t now = time(0);
// Convert now to tm struct for local timezone
tm* localtm = localtime(&now);
cout << "The local date and time is: " << asctime(localtm) << endl;
// Convert now to tm struct for UTC
tm* gmtm = gmtime(&now);
if (gmtm != NULL) {
cout << "The UTC date and time is: " << asctime(gmtm) << endl;
}
else {
cerr << "Failed to get the UTC date and time" << endl;
return EXIT_FAILURE;
}