boost ptime转化为时间字符串

    //对象的定义
    boost::posix_time::ptime p(boost::gregorian::date(2010, 3, 5)); //2010年3月5号0点
    boost::posix_time::ptime p1(boost::gregorian::date(2010, 3, 5), boost::posix_time::hours(1)); //2010年3月5号1点
    boost::posix_time::ptime p2 = boost::posix_time::time_from_string("2010-3-5 01:00:00");
    boost::posix_time::ptime p3 = boost::posix_time::from_iso_string("20100505T010000");

    //获取当前时间
    boost::posix_time::ptime p4 = boost::posix_time::second_clock::local_time(); //本地时间,秒精度
    cout << p4 << endl; //可以直接输出ptime,2018-Apr-11 16:23:54
    //boost::posix_time::ptime p4 = boost::posix_time::microsec_clock::local_time(); //本地时间,微妙精度,2018-Apr-11 08:23:54.986535
    //boost::posix_time::ptime p4 = boost::posix_time::second_clock::universal_time(); //UTC时间,微妙精度

    //获取字符串表示
    cout << boost::posix_time::to_iso_extended_string(p) << endl; //输出为2010-03-05T00:00:00
    cout << boost::posix_time::to_iso_string(p) << endl; //输出为20100305T000000
    cout << boost::posix_time::to_simple_string(p) << endl; //输出为2010-Mar-05 00:00:00

注意:ptime类型可以直接可以打印出来!!!!!!

毫秒转化为年月日时分秒时间:

std::string time_to_string(const boost::posix_time::ptime& time)
{
	boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
	facet->format("%Y_%m_%d %H_%M_%S");
	std::stringstream stream;
	stream.imbue(std::locale(std::locale::classic(), facet));
	stream << time;
	return stream.str();
}

使用ptime转化为毫秒:

	boost::posix_time::ptime pt = boost::posix_time::second_clock::universal_time();
	boost::posix_time::ptime epoch(boost::gregorian::date(1970, boost::gregorian::Jan, 1));
	std::cout << (pt - epoch).total_milliseconds() << std::endl;
	std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() << std::endl;

毫秒转化为日期:

int64_t milli = timestamp + (int64_t)8 * 60 * 60 * 1000;//此处转化为东八区北京时间,如果是其它时区需要按需求修改
auto mTime = std::chrono::milliseconds(milli);
auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(mTime);
auto tt = std::chrono::system_clock::to_time_t(tp);
std::tm* now = std::gmtime(&tt);
char* buf[512] = {0};
sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec);

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值