Gibt es eine plattformübergreifende Möglichkeit, das aktuelle Datum und die Uhrzeit in C++ abzurufen?
C++ teilt seine Datum/Uhrzeit-Funktionen mit C. Die tm-Struktur ist für einen C++-Programmierer wahrscheinlich am einfachsten zu handhaben - das folgende Beispiel gibt das heutige Datum aus:
#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";
}
std C-Bibliotheken bieten time()
.
Diese ist Sekunden von der Epoche entfernt und kann mit Standard-C-Funktionen in Datum und H:M:S
umgewandelt werden. Boost hat auch eine Zeit/Datum-Bibliothek, die Sie überprüfen können.
time_t timev;
time(&timev);
die C++-Standardbibliothek bietet keinen eigenen Datumstyp. C++ erbt die Strukturen und Funktionen für die Datums- und Zeitmanipulation von C, zusammen mit einer Reihe von Datums-/Zeit-Eingabe- und Ausgabefunktionen, die die Lokalisierung berücksichtigen.
// 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;
}