Reputation: 20684
How can I get current date time of the systems in seconds in C++?
I tried this one:
struct tm mytm = { 0 };
time_t result;
result = mktime(&mytm);
printf("%lld\n", (long long) result);
but I got: -1?
Upvotes: 19
Views: 91656
Reputation: 130
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);
Upvotes: 1
Reputation: 165
possibly a simpler version of example provided by @Zeta
time_t time_since_epoch()
{
auto now = std::chrono::system_clock::now();
return std::chrono::system_clock::to_time_t( now );
}
Upvotes: 3
Reputation: 68908
I'm using below function with few minor enhancements but as other have suggested definition of epoch might not be portable. For GCC it returns seconds as double value since Unix epoch but in VC++ it returns value since machine boot time. If your goal is just to get some value to do diff between two timestamps without persisting and sharing them, this should be ok however. If you need to persist or share timestamps then I would suggest to explicitly subtract some epoch from now() to get the duration object to be 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();
}
Upvotes: 1
Reputation: 105975
C++11 version, which ensures that the representation of ticks 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;
}
Upvotes: 13
Reputation: 1190
/* 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;
}
Upvotes: 22
Reputation: 1190
Try this: I hope it will work 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;
}
Upvotes: 6