C++使用Boost库对时间的操作

0x00、获取当前时间,时间格式为yyyy-MM-dd hh:mm:ss.zzz

std::string GetCurrentTime()
{
    // 使用本地时间
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

    // 获取毫秒部分
    boost::posix_time::time_duration td = now.time_of_day();
    unsigned int ms = td.total_milliseconds() % 1000; // 获取毫秒部分

    // 创建一个输出格式
    // std::locale loc(std::locale(), new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S.%f"));
    std::locale loc(std::locale(), new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S"));

    std::ostringstream oss;
    oss.imbue(loc);
    oss << now << "." << std::setw(3) << std::setfill('0') << ms % 1000;

    return oss.str();
}

0x01、获取当前时间,时间格式为 yyyy/MM/dd hh:mm:ss AM/PM,12小时时间制

std::string GetCurrentTimeFor12HFormat()
{
    boost::posix_time::ptime utc_now = boost::posix_time::second_clock::local_time();
    std::stringstream ss;
    ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_facet("%Y/%m/%d %I:%M:%S %p")));
    ss << utc_now;

    return ss.str();
}

0x02、获取当前时间,时间格式为 yyyy/MM/dd hh:mm:ss,24小时时间制

std::string GetCurrentTimeFor24HFormat()
{
    boost::posix_time::ptime utc_now = boost::posix_time::second_clock::local_time();
    std::stringstream ss;
    ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_facet("%Y/%m/%d %H:%M:%S")));
    ss << utc_now;

    return ss.str();
}

0x03、获取当前时间的总秒数

long GetCurrentTimeForSeconds()
{
    // 获取当前的UTC时间
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();

    // 计算自1970年1月1日以来的总秒数
    boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
    boost::posix_time::time_duration duration_since_epoch = now - epoch;

    // 返回总秒数
    return duration_since_epoch.total_seconds();
}

0x04、完整代码

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

using namespace std;

// yyyy-MM-dd hh:mm:ss.zzz
std::string GetCurrentTime()
{
    // 使用本地时间
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

    // 获取毫秒部分
    boost::posix_time::time_duration td = now.time_of_day();
    unsigned int ms = td.total_milliseconds() % 1000; // 获取毫秒部分

    // 创建一个输出格式
    // std::locale loc(std::locale(), new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S.%f"));
    std::locale loc(std::locale(), new boost::posix_time::time_facet("%Y-%m-%d %H:%M:%S"));

    std::ostringstream oss;
    oss.imbue(loc);
    oss << now << "." << std::setw(3) << std::setfill('0') << ms % 1000;

    return oss.str();
}

std::string GetCurrentTimeFor12HFormat()
{
    boost::posix_time::ptime utc_now = boost::posix_time::second_clock::local_time();
    std::stringstream ss;
    ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_facet("%Y/%m/%d %I:%M:%S %p")));
    ss << utc_now;

    return ss.str();
}

long ConvertFormatTime12HToSeconds(const std::string& datetimeStr)
{
    std::istringstream iss(datetimeStr);
    std::string year, month, day, hour, minute, second, period;

    getline(iss, year, '/');
    getline(iss, month, '/');
    getline(iss, day, ' ');
    getline(iss, hour, ':');
    getline(iss, minute, ':');
    getline(iss, second, ' ');
    getline(iss, period);

    // printf("%s-%s-%s %s:%s:%s %s\n", year.c_str(), month.c_str(), day.c_str(),
    //        hour.c_str(), minute.c_str(), second.c_str(), period.c_str());

    int i_year = std::stoi(year);
    int i_month = std::stoi(month);
    int i_day = std::stoi(day);
    int i_hour = std::stoi(hour);
    int i_minute = std::stoi(minute);
    int i_second = std::stoi(second);
    if(period == "PM")
    {
        i_hour += 12;
    }

    // printf("%d-%d-%d %d:%d:%d\n", i_year, i_month, i_day,
    //        i_hour, i_minute, i_second);

    boost::posix_time::ptime pt(boost::gregorian::date(i_year, i_month, i_day), boost::posix_time::time_duration(i_hour - 8, i_minute, i_second));

    time_t unix_time = boost::posix_time::to_time_t(pt);

    return unix_time;
}

std::string GetCurrentTimeFor24HFormat()
{
    boost::posix_time::ptime utc_now = boost::posix_time::second_clock::local_time();
    std::stringstream ss;
    ss.imbue(std::locale(ss.getloc(), new boost::posix_time::time_facet("%Y/%m/%d %H:%M:%S")));
    ss << utc_now;

    return ss.str();
}

long ConvertFormatTime24HToSeconds(const std::string& datetimeStr)
{
    // 解析日期时间字符串
    boost::posix_time::ptime parsed_time;

    std::istringstream iss(datetimeStr);
    iss.imbue(std::locale(iss.getloc(), new boost::posix_time::time_input_facet("%Y/%m/%d %H:%M:%S")));
    iss >> parsed_time;

    if (iss.fail())
    {
        printf("Failed to parse the date/time string.\n");
        return -1;
    }

    // 获取本地时间相对于UTC的偏移量
    boost::posix_time::ptime local_time = boost::posix_time::second_clock::local_time();
    boost::posix_time::ptime utc_time = boost::posix_time::second_clock::universal_time();
    // 获取偏移量
    boost::posix_time::time_duration timezone_offset = local_time - utc_time;
    // 调整解析出的时间以匹配UTC时间
    parsed_time -= timezone_offset;

    boost::posix_time::time_duration duration_since_epoch = parsed_time - boost::posix_time::ptime(boost::gregorian::date(1970, boost::gregorian::Jan, 1));
    long total_seconds = duration_since_epoch.total_seconds();

    return total_seconds;
}

long GetCurrentTimeForSeconds()
{
    // 获取当前的UTC时间
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();

    // 计算自1970年1月1日以来的总秒数
    boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
    boost::posix_time::time_duration duration_since_epoch = now - epoch;

    // 返回总秒数
    return duration_since_epoch.total_seconds();
}

std::string FormatTimeForSeconds(long seconds)
{
    boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
    boost::posix_time::time_duration td = boost::posix_time::seconds(seconds);;
    boost::posix_time::ptime now = epoch + td;

    // 格式化日期和时间
    std::ostringstream oss;
    oss << now.date().year() << "-"
        << std::setw(2) << std::setfill('0') << now.date().month().as_number() << "-"
        << std::setw(2) << std::setfill('0') << now.date().day().as_number() << " "
        << std::setw(2) << std::setfill('0') << now.time_of_day().hours() + 8 << ":"
        << std::setw(2) << std::setfill('0') << now.time_of_day().minutes() << ":"
        << std::setw(2) << std::setfill('0') << now.time_of_day().seconds();

    return oss.str();
}

long long GetCurrentTimeForMilliSeconds()
{
    // 获取当前的UTC时间
    boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();

    // 计算自1970年1月1日以来的总秒数
    boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
    boost::posix_time::time_duration duration_since_epoch = now - epoch;

    // 返回总秒数
    return duration_since_epoch.total_milliseconds();
}

std::string FormatTimeForMilliSeconds(long long milliseconds)
{
    // 创建一个 Boost ptime 对象
    boost::posix_time::ptime epoch(boost::gregorian::date(1970, 1, 1));
    boost::posix_time::time_duration td = boost::posix_time::milliseconds(milliseconds);
    boost::posix_time::ptime now = epoch + td;

    // 格式化日期和时间
    std::ostringstream oss;
    oss << now.date().year() << "-"
        << std::setw(2) << std::setfill('0') << now.date().month().as_number() << "-"
        << std::setw(2) << std::setfill('0') << now.date().day() << " "
        << std::setw(2) << std::setfill('0') << now.time_of_day().hours() + 8  << ":"
        << std::setw(2) << std::setfill('0') << now.time_of_day().minutes() << ":"
        << std::setw(2) << std::setfill('0') << now.time_of_day().seconds() << "."
        << std::setw(3) << std::setfill('0') << (now.time_of_day().fractional_seconds() / 1000);

    return oss.str();
}

int main()
{
    cout << "------------0#--------------" << endl;
    cout << GetCurrentTime() << endl;

    cout << "------------1#--------------" << endl;
    cout << GetCurrentTimeFor12HFormat() << endl;
    cout << GetCurrentTimeFor24HFormat() << endl;
    cout << "--------------------------" << endl;
    cout << ConvertFormatTime12HToSeconds(GetCurrentTimeFor12HFormat()) << endl;
    cout << ConvertFormatTime24HToSeconds(GetCurrentTimeFor24HFormat()) << endl;

    cout << "-------------2#-------------" << endl;
    cout << GetCurrentTimeForSeconds() << endl;
    cout << FormatTimeForSeconds(GetCurrentTimeForSeconds()) << endl;
    cout << "--------------------------" << endl;
    cout << GetCurrentTimeForMilliSeconds() << endl;
    cout << FormatTimeForMilliSeconds(GetCurrentTimeForMilliSeconds()) << endl;

    getchar();
    return 0;
}

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓琴儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值