Boost获取当前时间并格式化为字符串

格式化为字符串

时间转字符串有两种方法

#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

std::string getCurrentTime() {
    boost::posix_time::ptime currentTime = boost::posix_time::microsec_clock::local_time();    
    std::string formattedTime = boost::posix_time::to_iso_extended_string(currentTime);
    return formattedTime;
}

int main() {
    std::string currentTime = getCurrentTime();
    std::cout << "Current time: " << currentTime << std::endl;
    
    return 0;
}

格式化为指定格式字符串

#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <sstream>

std::string formatTime(const boost::posix_time::ptime& time, const std::string& format) {
    std::ostringstream oss;
    boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
    facet->format(format.c_str());
    oss.imbue(std::locale(std::cout.getloc(), facet));
    oss << time;
    return oss.str();
}

int main() {
    boost::posix_time::ptime currentTime = boost::posix_time::microsec_clock::local_time();
    std::string formattedTime = formatTime(currentTime, "%Y-%m-%d %H:%M:%S.%f");
    std::cout << "Formatted time: " << formattedTime << std::endl;
    
    return 0;
}

字符串转时间

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

int main() {
    std::string formattedString = "2021-09-30 10:30:00";
    boost::posix_time::ptime time = boost::posix_time::time_from_string(formattedString);

    std::cout << "Converted time: " << time << std::endl;

    return 0;
}

指定格式字符串转为时间

#include <iostream>
#include <sstream>
#include <locale>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/time_facet.hpp>

int main() {
    std::string formattedString = "2021-09-30 10:30:00";
    std::istringstream iss(formattedString);
    iss.imbue(std::locale(iss.getloc(), new boost::posix_time::time_input_facet("%Y-%m-%d %H:%M:%S")));

    boost::posix_time::ptime time;
    iss >> boost::posix_time::time_input(time);

    std::cout << "Converted time: " << time << std::endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值