UFO ET IT

std :: chrono를 사용하여 C ++에서 날짜 및 시간 출력

ufoet 2020. 12. 25. 00:16
반응형

std :: chrono를 사용하여 C ++에서 날짜 및 시간 출력


일부 오래된 코드를 업그레이드하고 가능한 경우 C ++ 11로 업데이트하려고했습니다. 다음 코드는 프로그램에서 시간과 날짜를 표시하는 방법입니다.

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

const std::string return_current_time_and_date() const
{
    time_t now = time(0);
    struct tm tstruct;
    char buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
    return buf;
}

std :: chrono (또는 이와 유사한)를 사용하여 현재 시간과 날짜를 비슷한 형식으로 출력하고 싶지만 그렇게하는 방법을 잘 모르겠습니다. 어떤 도움이라도 대단히 감사하겠습니다. 감사


<chrono>라이브러리 만 제외하고, 시간이 아닌 날짜를 다루는 system_clock자사의 시점들로 변환 할 수있는 기능을 가지고있는 time_t. 따라서 <chrono>날짜에 사용 하면 상황이 크게 개선되지 않습니다. 바라건대 우리는 chrono::date그리 멀지 않은 미래 와 같은 것을 얻길 바랍니다 .

<chrono>, 다음과 같은 방법으로 사용할 수 있습니다 .

#include <chrono>  // chrono::system_clock
#include <ctime>   // localtime
#include <sstream> // stringstream
#include <iomanip> // put_time
#include <string>  // string

std::string return_current_time_and_date()
{
    auto now = std::chrono::system_clock::now();
    auto in_time_t = std::chrono::system_clock::to_time_t(now);

    std::stringstream ss;
    ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
    return ss.str();
}

참고 std::localtime데이터 경주의 원인이 될 수 있습니다. localtime_r또는 귀하의 플랫폼에서 유사한 기능을 사용할 수 있습니다.

최신 정보:

새 버전의 Howard Hinnant 날짜 라이브러리사용하여 다음과 같이 작성할 수 있습니다.

#include "date.h"
#include <chrono>
#include <string>
#include <sstream>

std::string return_current_time_and_date() {
  auto now = std::chrono::system_clock::now();
  auto today = date::floor<days>(now);

  std::stringstream ss;
  ss << today << ' ' << date::make_time(now - today) << " UTC";
  return ss.str();
}

그러면 "2015-07-24 05 : 15 : 34.043473124 UTC"와 같은 내용이 출력됩니다.


관련없는 메모에서 constC ++ 11에서는 객체 반환 이 바람직하지 않습니다. const 반환 값은 이동할 수 없습니다. 후행 const는 멤버 함수에만 유효하고이 함수는 멤버 일 필요가 없기 때문에 후행 const도 제거했습니다.


예 :

#include <iostream>
#include <chrono>
#include <ctime>

std::string getTimeStr(){
    std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

    std::string s(30, '\0');
    std::strftime(&s[0], s.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
    return s;
}
int main(){

    std::cout<<getTimeStr()<<std::endl;
    return 0;

}

아래와 같이 출력 :

enter image description here


bames53 solutions are good, but do not compile on my VS2017. The solution with ctime does not compile because localtime is very deprecated. The one with date.h does not compile with the current date.h I just took off github even though the documentation says they should, because today cannot be streamed as is. I omitted the includes but here is code that works:

void TimeTest()
{
    auto n = std::chrono::system_clock::now();
    auto in_time_t = std::chrono::system_clock::to_time_t(n);
    std::tm buf;
    localtime_s(&buf, &in_time_t);
    std::cout << std::put_time(&buf, "%Y-%m-%d %X") << std::endl;

}

// I just added date.h from this link's guthub to the project.
// https://howardhinnant.github.io/date/date.html
void TimeTest1() {
    auto now = std::chrono::system_clock::now();
    auto today =  floor<date::days>(std::chrono::system_clock::now());
    std::cout << date::year_month_day{ today } << ' ' << date::make_time(now - today) << std::endl;
}

// output is 
// 2018-04-08 21:19:49
// 2018-04-08 18:19:49.8408289

Feel free to fix bames53 solution and delete mine. My text just won't fit in a comment. I'm sure it can save many people from grief.


For getting also milliseconds, I use chrono and C function localtime_r which is thread-safe (in opposition to std::localtime).

#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>


int main() {
  std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
  std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
  struct tm currentLocalTime;
  localtime_r(&currentTime, &currentLocalTime);
  char timeBuffer[80];
  std::size_t charCount { std::strftime( timeBuffer, 80,
                                         "%D %T",
                                          &currentLocalTime)
                         };

  if (charCount == 0) return -1;

  std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
  return 0;
}

For format: http://www.cplusplus.com/reference/ctime/strftime/


You can improve the answer from @bames53 by using Boost lexical_cast instead of string stream manipulations.

Here is what I do:

#include <boost/lexical_cast.hpp>
#include <ctime>

std::string return_current_time_and_date() {
    auto current_time = std::time(0);
    return boost::lexical_cast<std::string>(std::put_time(std::gmtime(& current_time), "%Y-%m-%d %X"));
}

ReferenceURL : https://stackoverflow.com/questions/17223096/outputting-date-and-time-in-c-using-stdchrono

반응형