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

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

#include <iostream>
#include <ctime>
#include <iomanip>
#include <sstream>
//字符串转时间戳
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值