如何在C ++中以秒为单位获取系统的当前日期时间?
我试过这个:
struct tm mytm = { 0 };
time_t result;
result = mktime(&mytm);
printf("%lld\n", (long long) result);
但我得到了:-1?
答案 0 :(得分:11)
/* 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;
}
答案 1 :(得分:6)
试试这个: 我希望它对你有用。
#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;
}
答案 2 :(得分:6)
C ++ 11版本,它确保刻度的表示实际上是一个整数:
#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;
}
答案 3 :(得分:1)
可能是@Zeta
提供的更简单的示例time_t time_since_epoch()
{
auto now = std::chrono::system_clock::now();
return std::chrono::system_clock::to_time_t( now );
}
答案 4 :(得分:0)
我正在使用下面的功能,只有很少的小改进,但正如其他人建议的epoch定义可能不是便携式的。对于GCC,它返回自Unix纪元以来的秒值,但在VC ++中它返回值,因为机器启动时间。如果你的目标只是获得一些值来在两个时间戳之间进行差异而不持久和共享它们,那么这应该没问题。如果你需要持久化或共享时间戳,那么我建议从now()中明确减去一些纪元,以使持续时间对象可移植。
//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();
}
答案 5 :(得分:0)
这将以秒为单位给出当前日期/时间,
#include <time.h>
time_t timeInSec;
time(&timeInSec);
PrintLn("Current time in seconds : \t%lld\n", (long long)timeInSec);