You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何生成mm/dd-hh:mm格式日期时间的两日后对应字符串

C++ 实现mm/dd-hh:mm格式时间偏移2天方案

核心原则:不要手动编写月份天数判断、闰年判断、跨月跨年进位逻辑,这类手动实现极易在2月、大小月、年末场景出边界bug,直接使用成熟时间库的解析、偏移、格式化能力即可,所有复杂日期逻辑由库自动处理。


前置说明

输入格式mm/dd-hh:mm不包含年份信息,而日期跨2月末、年末的偏移计算强依赖年份(比如2月28日加两天,平年是3月2日,闰年是3月1日;12月31日加两天是次年1月2日),因此计算前需要根据业务规则补全该日期对应的年份(比如默认取当前自然年,若解析出的日期早于当前日期阈值则归为下一年)。


方案1:C++20 标准库实现(推荐,无第三方依赖)

C++20 新增的std::chrono扩展库原生支持自定义格式时间解析、时间点算术运算、格式化输出,接口简洁且无额外依赖,只要前后使用一致的时区规则就不会出现时间偏差。

#include <chrono>
#include <string>
#include <string_view>
#include <sstream>
#include <format>
#include <stdexcept>

std::string add_two_days(std::string_view input, int target_year) {
    std::chrono::local_time<std::chrono::minutes> tp;
    std::istringstream iss(input.data());
    
    // 按mm/dd-hh:mm格式解析,%m=两位月 %d=两位日 %H=24制小时 %M=分钟
    iss >> std::chrono::parse("%m/%d-%H:%M", tp);
    if (iss.fail()) {
        throw std::invalid_argument("输入时间不符合mm/dd-hh:mm格式要求");
    }

    // 直接偏移2天,库自动处理闰年、大小月、跨年进位
    auto offset_tp = tp + std::chrono::days(2);
    // 格式化回目标格式,自动补前导零
    return std::format("{:%m/%d-%H:%M}", offset_tp);
}

方案2:旧标准C兼容实现(C11~C++17可用)

如果项目暂不支持C++20,可直接使用C标准库的tm结构+mktime接口实现,mktime原生支持非法日期字段的自动修正,不需要手动处理进位逻辑。

#include <ctime>
#include <string>
#include <string_view>
#include <sstream>
#include <iomanip>
#include <stdexcept>

std::string add_two_days_legacy(std::string_view input, int target_year) {
    std::tm t{};
    // tm_year存储的是1900年起的年份偏移
    t.tm_year = target_year - 1900;
    std::istringstream iss(input.data());
    char split_char;

    // 分段解析月/日、时:分
    iss >> std::get_time(&t, "%m/%d");
    iss >> split_char;
    iss >> std::get_time(&t, "%H:%M");
    if (iss.fail()) {
        throw std::invalid_argument("输入时间不符合mm/dd-hh:mm格式要求");
    }

    // 直接给日字段加2,哪怕值超出当月天数也没关系
    t.tm_mday += 2;
    // mktime自动修正所有字段:处理跨月、跨年、闰年进位,同时自动计算星期、当年天数等字段
    std::mktime(&t);

    std::ostringstream oss;
    oss << std::put_time(&t, "%m/%d-%H:%M");
    return oss.str();
}

注意:如果业务使用UTC时间,调用mktime前需要将全局时区设置为UTC,避免本地时区、夏令时导致的时间偏移误差。


效果验证

几个典型边界场景的计算结果:

  • 平年输入02/28-13:45,输出03/02-13:45
  • 闰年输入02/28-13:45,输出03/01-13:45
  • 年末输入12/31-23:59,输出01/02-23:59(自动进位到下一年)
  • 小月月末输入04/30-09:10,输出05/02-09:10

内容的提问来源于stack exchange,提问作者Fabio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 23:18:48