developer tip

C ++로 Unix 타임 스탬프 얻기

copycodes 2021. 1. 6. 08:32
반응형

C ++로 Unix 타임 스탬프 얻기


uintC ++에서 유닉스 타임 스탬프를 어떻게 얻 습니까? 나는 조금 봤는데 대부분의 방법이 시간을 나타내는 더 복잡한 방법을 찾고있는 것 같습니다. 나는 그것을 얻을 수 uint없습니까?


time()가장 간단한 함수-Epoch 이후 초. 여기에 Linux 맨 페이지가 있습니다 .

위에 링크 된 cppreference 페이지는 다음 예를 제공합니다 .

#include <ctime>
#include <iostream>

int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::asctime(std::localtime(&result))
              << result << " seconds since the Epoch\n";
}

#include<iostream>
#include<ctime>

int main()
{
    std::time_t t = std::time(0);  // t is an integer type
    std::cout << t << " seconds since 01-Jan-1970\n";
    return 0;
}

가장 일반적인 조언은 잘못된 것 time()입니다.. 즉 상대 타이밍 사용되는 : ISO C ++가 지정하지 않는 1970-01-01T00:00Z것입니다time_t(0)

더 나쁜 것은 당신이 그것을 쉽게 알아낼 수 없다는 것입니다. 물론 time_t(0)with 의 달력 날짜를 찾을 수 있습니다 gmtime.하지만 그럴 경우 2000-01-01T00:00Z어떻게 하시겠습니까? 1970-01-01T00:00Z사이에 몇 초가 있었 2000-01-01T00:00Z습니까? 윤초로 인해 확실히 60의 배수가 아닙니다.


#include <iostream>
#include <sys/time.h>

using namespace std;

int main ()
{
  unsigned long int sec= time(NULL);
  cout<<sec<<endl;
}

Windows는 다른 epoch 및 시간 단위를 사용합니다. Unix / Linux에서 Windows 파일 시간 을 초로 변환 참조

Windows에서 std :: time () 반환하는 것은 (아직) 나에게 알려지지 않았습니다 (;-))


더 많은 정보로 전역 정의를 만들었습니다.

#include <iostream>
#include <ctime>
#include <iomanip>

#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILE__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "

static std::time_t time_now = std::time(nullptr);

다음과 같이 사용하십시오.

INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;

샘플 출력 :

16-06-23 21:33:19 [INFO] src/main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] src/main.cpp(main:7) >> Goodbye world

이 줄을 헤더 파일에 넣으십시오. 디버깅 등에 매우 유용합니다.


이것이 Google의 첫 번째 결과이고 아직 C ++ 11 답변이 없으므로 std :: chrono를 사용하여이를 수행하는 방법은 다음과 같습니다.

    #include <chrono>

    ...

    using namespace std::chrono;
    int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

Note that this answer doesn't guarantee that the epoch is 1/1/1970, but in practice it is very likely to be.

ReferenceURL : https://stackoverflow.com/questions/6012663/get-unix-timestamp-with-c

반응형