如何以秒为单位获取系统的当前日期时间

oli*_*dev 9 c++

如何在C++中以秒为单位获取系统的当前日期时间?

我试过这个:

struct tm mytm = { 0 };
time_t result;

result = mktime(&mytm);

printf("%lld\n", (long long) result); 
Run Code Online (Sandbox Code Playgroud)

但我得到了:-1?

Asm*_*ita 12

/* 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;
}
Run Code Online (Sandbox Code Playgroud)


Zet*_*eta 7

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;
}
Run Code Online (Sandbox Code Playgroud)


Asm*_*ita 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;
}
Run Code Online (Sandbox Code Playgroud)