C++时间日期类型与std::string互转

本文介绍了如何使用C++标准库将字符串转换为`std::chrono::system_clock::time_point`,分别处理日期和日期时间,包括解析年月日和小时分钟秒,以及处理包含毫秒的时间格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::chrono::system_clock::time_point StringtoDate(std::string date)
{
    std::string year = date.substr(0, 4);
    std::string month = date.substr(4, 2);
    std::string day = date.substr(6, 2);
    tm tmObj;
    tmObj.tm_year = std::atoi(year.c_str()) - 1900;
    tmObj.tm_mon = std::atoi(month.c_str()) - 1;
    tmObj.tm_mday = std::atoi(day.c_str());
    tmObj.tm_hour = std::atoi("0");
    tmObj.tm_min = std::atoi("0");
    tmObj.tm_sec = std::atoi("0");

    //std::time_t tt = mktime(&tmObj);
    return std::chrono::system_clock::from_time_t(mktime(&tmObj));
}
std::chrono::system_clock::time_point StringtoDateTime(std::string date, std::string time)
{
    std::string year = date.substr(0, 4);
    std::string month = date.substr(4, 2);
    std::string day = date.substr(6, 2);
    std::string hour = time.substr(0, 2);
    std::string min = time.substr(2, 2);
    std::string sec = time.substr(4, 2);

    tm tmObj;
    tmObj.tm_year = std::atoi(year.c_str()) - 1900;
    tmObj.tm_mon = std::atoi(month.c_str()) - 1;
    tmObj.tm_mday = std::atoi(day.c_str());
    tmObj.tm_hour = std::atoi(hour.c_str());
    tmObj.tm_min = std::atoi(min.c_str());
    tmObj.tm_sec = std::atoi(sec.c_str());

    size_t pos = time.find(".", 0);
    if (pos == std::string::npos)
    {
        return std::chrono::system_clock::from_time_t(std::mktime(&tmObj));
    }
    else
    {
        std::string strMS = time.substr(pos + 1, time.length() - pos - 1);
        long long ms = std::atoll(strMS.c_str());
        return (std::chrono::system_clock::from_time_t(std::mktime(&tmObj)) + std::chrono::microseconds(ms));
    }   
}
std::string DatetoString(std::chrono::system_clock::time_point timePoint)
{
    std::time_t tt = std::chrono::system_clock::to_time_t(timePoint);
    std::stringstream ss;
    ss << std::put_time(std::localtime(&tt), "%Y%m%d");
    return ss.str();
}
std::string TimetoString(std::chrono::system_clock::time_point timePoint)
{
    std::time_t tt = std::chrono::system_clock::to_time_t(timePoint);

    auto ms = timePoint.time_since_epoch();
    auto diff = std::chrono::duration_cast<std::chrono::microseconds>(ms).count();
    auto const mcsecs = diff % 1000000;

    std::stringstream ss;
    if (mcsecs == 0)
    {
        ss << std::put_time(std::localtime(&tt), "%H%M%S");
    }
    else
    {
        ss << std::put_time(std::localtime(&tt), "%H%M%S") << "." << mcsecs;
    }
    return ss.str();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值