C++11 印出現在時間 - 使用 chrono, localtime_s, put_time, generic in CharT

template<typename CharT>
std::basic_string<CharT> now_as_string(const CharT* fmt)
{
  auto now = std::chrono::system_clock::now();                  // as chrono time_point
  auto now_time_t = std::chrono::system_clock::to_time_t(now);  // as UNIX-timestamp integer
  std::tm now_tm = {};                                          // as struct with date and time
  localtime_s(&now_tm, &now_time_t);                            // use thread-safe localtime
  std::basic_ostringstream<CharT> ss;                           // as C++ stream
  ss << std::put_time(&now_tm, fmt);                            // date-time string formatter
                                                                // fmt ex. `%F %T` 
                                                                // to be `2016-05-31 13:01:02`
  return ss.str();
}
Usage
std::cout << "Time: " << now_as_string("%F %T") << std::endl;
Output
Time: 2016-05-31 14:04:04
put_time like 版本, 直送 stream, 減少 string copy
template<typename CharT>
std::basic_ostream<CharT>& now_as_stream(const CharT* fmt, std::basic_ostream<CharT>& out)
{
  auto now = std::chrono::system_clock::now();                  // as chrono time_point
  auto now_time_t = std::chrono::system_clock::to_time_t(now);  // as UNIX-timestamp integer
  std::tm now_tm = {};                                          // as struct with date and time
  localtime_s(&now_tm, &now_time_t);                            // use thread-safe localtime
  out << std::put_time(&now_tm, fmt);                            // date-time string formatter
                                                                // fmt ex. `%F %T` 
                                                                // to be `2016-05-31 13:01:02`
 return out;
}

template<typename CharT>
struct now_as_type
{
  now_as_type(const CharT* fmt) : m_fmt(fmt) {}
  const CharT* m_fmt;

  friend static std::basic_ostream<typename CharT>& operator<< (std::basic_ostream<typename CharT>& lhs, const now_as_type& rhs)
  {
    return now_as_stream(rhs.m_fmt, lhs);
  }
};

template<typename CharT>
now_as_type<CharT> put_now(const CharT* fmt) { return now_as_type<CharT>(fmt); }

Usage
std::cout << put_now("%F %T") << std::endl;

Reference:

comments powered by Disqus