c++标准库时间戳和字符串转换

我们在开发中经常遇到,时间戳和字符串间的相互转换。每次都要去写一个新的,不如把日常用的记录下来,供以后直接使用。下面就是一个简单的实现。

#include 
#include 
#include 
#include 
//字符串转时间戳
template<typename CHAR>
__time64_t Str2Timestamp(const CHAR* str, const CHAR* fmt)
{
  std::basic_istringstream<CHAR> is(str);
  std::tm tm = {};
  is >> std::get_time(&tm, fmt);

  return std::mktime(&tm);
}

//时间戳转字符串
template<typename CHAR>
std::basic_string<CHAR> Timestamp2Str(__time64_t timestamp,const CHAR* fmt)
{
  std::tm cur_tm = *(std::localtime(&timestamp));

  std::basic_ostringstream<CHAR> os;
  os << std::put_time(&cur_tm, fmt);

  return os.str();
}
//测试
int main()
{
  std::string str_timestamp = Timestamp2Str(time(NULL), "%Y:%m:%d %H:%M:%S").c_str();
  std::cout << str_timestamp << std::endl;

  std::cout << Str2Timestamp(str_timestamp.c_str(),"%Y:%m:%d %H:%M:%S") << std::endl;
}

你可能感兴趣的:(c++标准库时间处理,c++,visual,studio,开发语言)