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);

猜你喜欢

转载自blog.csdn.net/qq_23350817/article/details/109057180
今日推荐