Gibt es einen plattformübergreifenden Weg, um das aktuelle Datum und die aktuelle Uhrzeit in C++ abzurufen?
In C++ 11 können Sie std::chrono::system_clock::now()
verwenden.
Beispiel (kopiert von de.cppreference.com ):
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
auto start = std::chrono::system_clock::now();
// Some computation here
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << elapsed_seconds.count() << "s\n";
}
Das sollte so etwas drucken:
finished computation at Mon Oct 2 00:59:08 2017
elapsed time: 1.88232s
C++ teilt seine Datums-/Zeitfunktionen mit C. Die Struktur " tm" ist wahrscheinlich die einfachste für einen C++ - Programmierer, mit der Sie arbeiten können. Das folgende Datum 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";
}
Sie können den folgenden plattformübergreifenden Code ausprobieren, um das aktuelle Datum und die aktuelle Uhrzeit abzurufen:
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
int main() {
std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
getchar(); // wait for keyboard input
}
Ausgabe:
currentDateTime()=2012-05-06.21:47:59
Bitte besuchen Sie hier für weitere Informationen zum Datums-/Zeitformat
die C++ - Standardbibliothek bietet keinen richtigen Datumstyp. C++ erbt die Strukturen und Funktionen für die Datums- und Uhrzeitbearbeitung von C sowie einige Eingabe- und Ausgabefunktionen für Datum und Uhrzeit, 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;
}
Neue Antwort auf eine alte Frage:
Die Frage gibt nicht an, in welcher Zeitzone. Es gibt zwei sinnvolle Möglichkeiten:
Für 1 können Sie diese Datumsbibliothek und das folgende Programm verwenden:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
std::cout << system_clock::now() << '\n';
}
Was gerade für mich ausgegeben wird:
2015-08-18 22:08:18.944211
Die Datumsbibliothek fügt im Wesentlichen nur einen Streaming-Operator für std::chrono::system_clock::time_point
hinzu. Es fügt auch eine Menge weiterer Nice-Funktionen hinzu, die in diesem einfachen Programm jedoch nicht verwendet werden.
Wenn Sie 2 (die Ortszeit) bevorzugen, gibt es eine timezone-Bibliothek , die auf der date-Bibliothek aufbaut. Beide Bibliotheken sind open source und cross platform, sofern der Compiler C++ 11 oder C++ 14 unterstützt.
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
auto local = make_zoned(current_zone(), system_clock::now());
std::cout << local << '\n';
}
Was für mich gerade ausgegeben wird:
2015-08-18 18:08:18.944211 EDT
Der Ergebnistyp aus make_zoned
ist ein date::zoned_time
, der eine Kombination aus date::time_zone
und std::chrono::system_clock::time_point
darstellt. Dieses Paar stellt eine lokale Zeit dar, kann jedoch auch UTC darstellen, je nachdem, wie Sie es abfragen.
Mit der obigen Ausgabe können Sie feststellen, dass sich mein Computer derzeit in einer Zeitzone mit einem UTC-Offset von -4h und einer Abkürzung für EDT befindet.
Wenn eine andere Zeitzone gewünscht wird, kann dies ebenfalls durchgeführt werden. Um beispielsweise die aktuelle Uhrzeit in Sydney, Australien, zu ermitteln, ändern Sie einfach die Konstruktion der Variablen local
in:
auto local = make_zoned("Australia/Sydney", system_clock::now());
Und die Ausgabe ändert sich zu:
2015-08-19 08:08:18.944211 AEST
(Für andere Googler)
Es gibt auch Boost :: date_time :
#include <boost/date_time/posix_time/posix_time.hpp>
boost::posix_time::ptime date_time = boost::posix_time::microsec_clock::universal_time();
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
auto time = std::time(nullptr);
std::cout << std::put_time(std::localtime(&time), "%F %T%z"); // ISO 8601 format.
Rufen Sie die aktuelle Uhrzeit entweder mit std::time()
oder std::chrono::system_clock::now()
(oder einem anderen Uhrentyp ) ab.
std::put_time()
(C++ 11) und strftime()
(C) bieten viele Formatierer zur Ausgabe dieser Zeiten.
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout
// ISO 8601: %Y-%m-%d %H:%M:%S, e.g. 2017-07-31 00:42:00+0200.
<< std::put_time(std::gmtime(&time), "%F %T%z") << '\n'
// %m/%d/%y, e.g. 07/31/17
<< std::put_time(std::gmtime(&time), "%D");
}
Die Reihenfolge der Formatierungen ist wichtig:
std::cout << std::put_time(std::gmtime(&time), "%c %A %Z") << std::endl;
// Mon Jul 31 00:00:42 2017 Monday GMT
std::cout << std::put_time(std::gmtime(&time), "%Z %c %A") << std::endl;
// GMT Mon Jul 31 00:00:42 2017 Monday
Die Formatierer von strftime()
sind ähnlich:
char output[100];
if (std::strftime(output, sizeof(output), "%F", std::gmtime(&time))) {
std::cout << output << '\n'; // %Y-%m-%d, e.g. 2017-07-31
}
Oft bedeutet der Großformatierer "Vollversion" und Kleinbuchstaben bedeuten Abkürzung (z. B. Y: 2017, y: 17).
Gebietsschemaeinstellungen ändern die Ausgabe:
#include <iomanip>
#include <iostream>
int main() {
auto time = std::time(nullptr);
std::cout << "undef: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_US.utf8"));
std::cout << "en_US: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("en_GB.utf8"));
std::cout << "en_GB: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("de_DE.utf8"));
std::cout << "de_DE: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ja_JP.utf8"));
std::cout << "ja_JP: " << std::put_time(std::gmtime(&time), "%c") << '\n';
std::cout.imbue(std::locale("ru_RU.utf8"));
std::cout << "ru_RU: " << std::put_time(std::gmtime(&time), "%c");
}
Mögliche Ausgabe ( Coliru , Compiler Explorer ):
undef: Tue Aug 1 08:29:30 2017
en_US: Tue 01 Aug 2017 08:29:30 AM GMT
en_GB: Tue 01 Aug 2017 08:29:30 GMT
de_DE: Di 01 Aug 2017 08:29:30 GMT
ja_JP: 2017年08月01日 08時29分30秒
ru_RU: Вт 01 авг 2017 08:29:30
Ich habe std::gmtime()
für die Konvertierung nach UTC verwendet. std::localtime()
wird zur Konvertierung in Ortszeit bereitgestellt.
Beachten Sie, dass asctime()
/ ctime()
, die in anderen Antworten erwähnt wurden, jetzt als veraltet markiert sind und strftime()
bevorzugt werden sollte.
Ja, und Sie können dies mit Formatierungsregeln tun, die durch das aktuell angefragte Gebietsschema angegeben werden:
#include <iostream>
#include <iterator>
#include <string>
class timefmt
{
public:
timefmt(std::string fmt)
: format(fmt) { }
friend std::ostream& operator <<(std::ostream &, timefmt const &);
private:
std::string format;
};
std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
std::ostream::sentry s(os);
if (s)
{
std::time_t t = std::time(0);
std::tm const* tm = std::localtime(&t);
std::ostreambuf_iterator<char> out(os);
std::use_facet<std::time_put<char>>(os.getloc())
.put(out, os, os.fill(),
tm, &mt.format[0], &mt.format[0] + mt.format.size());
}
os.width(0);
return os;
}
int main()
{
std::cout << timefmt("%c");
}
Ausgabe:
Fri Sep 6 20:33:31 2013
sie können die C++ 11-Zeitklasse verwenden:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());
cout << put_time(localtime(&now), "%F %T") << endl;
return 0;
}
ausgabe:
2017-08-25 12:30:08
Es gibt immer das Präpressormakro __TIMESTAMP__
.
#include <iostream>
using namespace std
void printBuildDateTime () {
cout << __TIMESTAMP__ << endl;
}
int main() {
printBuildDateTime();
}
beispiel: So Apr 13 11:28:08 2014
Ich fand diesen Link für meine Implementierung sehr nützlich: C++ - Datum und Uhrzeit
Hier ist der Code, den ich in meiner Implementierung verwende, um ein klares Ausgabeformat "YYYYMMDD HHMMSS" zu erhalten. Der Parameter ist für das Umschalten zwischen UTC und Ortszeit. Sie können meinen Code leicht an Ihre Bedürfnisse anpassen.
#include <iostream>
#include <ctime>
using namespace std;
/**
* This function gets the current date time
* @param useLocalTime true if want to use local time, default to false (UTC)
* @return current datetime in the format of "YYYYMMDD HHMMSS"
*/
string getCurrentDateTime(bool useLocalTime) {
stringstream currentDateTime;
// current date/time based on current system
time_t ttNow = time(0);
tm * ptmNow;
if (useLocalTime)
ptmNow = localtime(&ttNow);
else
ptmNow = gmtime(&ttNow);
currentDateTime << 1900 + ptmNow->tm_year;
//month
if (ptmNow->tm_mon < 9)
//Fill in the leading 0 if less than 10
currentDateTime << "0" << 1 + ptmNow->tm_mon;
else
currentDateTime << (1 + ptmNow->tm_mon);
//day
if (ptmNow->tm_mday < 10)
currentDateTime << "0" << ptmNow->tm_mday << " ";
else
currentDateTime << ptmNow->tm_mday << " ";
//hour
if (ptmNow->tm_hour < 10)
currentDateTime << "0" << ptmNow->tm_hour;
else
currentDateTime << ptmNow->tm_hour;
//min
if (ptmNow->tm_min < 10)
currentDateTime << "0" << ptmNow->tm_min;
else
currentDateTime << ptmNow->tm_min;
//sec
if (ptmNow->tm_sec < 10)
currentDateTime << "0" << ptmNow->tm_sec;
else
currentDateTime << ptmNow->tm_sec;
return currentDateTime.str();
}
Ausgabe (UTC, EST):
20161123 000454
20161122 190454
Sie können ctime()
auch direkt verwenden:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
printf ( "Current local time and date: %s", ctime (&rawtime) );
return 0;
}
Dies wurde für mich unter Linux (RHEL) und Windows (x64) für g ++ und OpenMP kompiliert:
#include <ctime>
#include <iostream>
#include <string>
#include <locale>
////////////////////////////////////////////////////////////////////////////////
//
// Reports a time-stamped update to the console; format is:
// Name: Update: Year-Month-Day_of_Month Hour:Minute:Second
//
////////////////////////////////////////////////////////////////////////////////
//
// [string] strName : name of the update object
// [string] strUpdate: update descripton
//
////////////////////////////////////////////////////////////////////////////////
void ReportTimeStamp(string strName, string strUpdate)
{
try
{
#ifdef _WIN64
// Current time
const time_t tStart = time(0);
// Current time structure
struct tm tmStart;
localtime_s(&tmStart, &tStart);
// Report
cout << strName << ": " << strUpdate << ": " << (1900 + tmStart.tm_year) << "-" << tmStart.tm_mon << "-" << tmStart.tm_mday << " " << tmStart.tm_hour << ":" << tmStart.tm_min << ":" << tmStart.tm_sec << "\n\n";
#else
// Current time
const time_t tStart = time(0);
// Current time structure
struct tm* tmStart;
tmStart = localtime(&tStart);
// Report
cout << strName << ": " << strUpdate << ": " << (1900 + tmStart->tm_year) << "-" << tmStart->tm_mon << "-" << tmStart->tm_mday << " " << tmStart->tm_hour << ":" << tmStart->tm_min << ":" << tmStart->tm_sec << "\n\n";
#endif
}
catch (exception ex)
{
cout << "ERROR [ReportTimeStamp] Exception Code: " << ex.what() << "\n";
}
return;
}
Das funktioniert mit G ++ Ich bin mir nicht sicher, ob dies Ihnen hilft. Programmausgabe:
The current time is 11:43:41 am
The current date is 6-18-2015 June Wednesday
Day of month is 17 and the Month of year is 6,
also the day of year is 167 & our Weekday is 3.
The current year is 2015.
Code:
#include <ctime>
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
using namespace std;
const std::string currentTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%H:%M:%S %P", &tstruct);
return buf;
}
const std::string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%B %A ", &tstruct);
return buf;
}
int main() {
cout << "\033[2J\033[1;1H";
std:cout << "The current time is " << currentTime() << std::endl;
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout << "The current date is " << now->tm_mon + 1 << '-'
<< (now->tm_mday + 1) << '-'
<< (now->tm_year + 1900)
<< " " << currentDate() << endl;
cout << "Day of month is " << (now->tm_mday)
<< " and the Month of year is " << (now->tm_mon)+1 << "," << endl;
cout << "also the day of year is " << (now->tm_yday)
<< " & our Weekday is " << (now->tm_wday) << "." << endl;
cout << "The current year is " << (now->tm_year)+1900 << "."
<< endl;
return 0;
}
http://www.cplusplus.com/reference/ctime/strftime/
Dieses eingebaute System scheint eine vernünftige Auswahl an Optionen zu bieten.
localtime_s () version:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t current_time;
struct tm local_time;
time ( ¤t_time );
localtime_s(&local_time, ¤t_time);
int Year = local_time.tm_year + 1900;
int Month = local_time.tm_mon + 1;
int Day = local_time.tm_mday;
int Hour = local_time.tm_hour;
int Min = local_time.tm_min;
int Sec = local_time.tm_sec;
return 0;
}
Mit dem folgenden Code können Sie das aktuelle Systemdatum und die aktuelle Uhrzeit in C++ abrufen:
#include <iostream>
#include <time.h> //It may be #include <ctime> or any other header file depending upon
// compiler or IDE you're using
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
// convert now to string form
string dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
return 0;
}
PS: Besuchen Sie diese Site für weitere Informationen.
#include <iostream>
#include <chrono>
#include <string>
#pragma warning(disable: 4996)
// Ver: C++ 17
// IDE: Visual Studio
int main() {
using namespace std;
using namespace chrono;
time_point tp = system_clock::now();
time_t tt = system_clock::to_time_t(tp);
cout << "Current time: " << ctime(&tt) << endl;
return 0;
}
#include <Windows.h>
void main()
{
//Following is a structure to store date / time
SYSTEMTIME SystemTime, LocalTime;
//To get the local time
int loctime = GetLocalTime(&LocalTime);
//To get the system time
int systime = GetSystemTime(&SystemTime)
}
Sie könnten boost
verwenden:
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
using namespace boost::gregorian;
int main()
{
date d = day_clock::universal_day();
std::cout << d.day() << " " << d.month() << " " << d.year();
}