How to find out the current system date and time in seconds

How can I get the current date and time of systems in seconds in C ++?

I tried this:

struct tm mytm = { 0 }; time_t result; result = mktime(&mytm); printf("%lld\n", (long long) result); 

but i got: -1?

+8
source share
6 answers
 /* time example */ #include <stdio.h> #include <time.h> int main () { time_t seconds; seconds = time (NULL); printf ("%ld seconds since January 1, 1970", seconds); return 0; } 
+11
source

Try the following: Hope this works for you.

 #include <iostream> #include <ctime> using namespace std; int main( ) { // current date/time based on current system time_t now = time(0); // convert now to string form char* dt = ctime(&now); cout << "The local date and time is: " << dt << endl; // convert now to tm struct for UTC tm *gmtm = gmtime(&now); dt = asctime(gmtm); cout << "The UTC date and time is:"<< dt << endl; } 
+6
source

C ++ 11 version, which ensures that the tick representation is actually an integral:

 #include <iostream> #include <chrono> #include <type_traits> std::chrono::system_clock::rep time_since_epoch(){ static_assert( std::is_integral<std::chrono::system_clock::rep>::value, "Representation of ticks isn't an integral value." ); auto now = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::seconds>(now).count(); } int main(){ std::cout << time_since_epoch() << std::endl; } 
+6
source

I use the function below with a few minor improvements, but others claim the definition of an era may not be portable. For GCC, it returns seconds as a double value from the time of Unix, but in VC ++ it returns the value from the moment the machine boots. If your goal is simply to get some value in order to make the difference between the two timestamps without storing or separating them, this should be fine. If you need to save or share timestamps, I would suggest explicitly subtracting some era from now () so that the duration object is portable.

 //high precision time in seconds since epoch static double getTimeSinceEpoch(std::chrono::high_resolution_clock::time_point* t = nullptr) { using Clock = std::chrono::high_resolution_clock; return std::chrono::duration<double>((t != nullptr ? *t : Clock::now() ).time_since_epoch()).count(); } 
0
source

possibly a simpler version of the example provided by @Zeta p>

 time_t time_since_epoch() { auto now = std::chrono::system_clock::now(); return std::chrono::system_clock::to_time_t( now ); } 
0
source

This will give the current date / time in seconds,

 #include <time.h> time_t timeInSec; time(&timeInSec); PrintLn("Current time in seconds : \t%lld\n", (long long)timeInSec); 
0
source

All Articles