简体   繁体   English

比较 C++ 中的 DayTime 字符串

[英]Compare DayTime strings in C++

如果我有一个以“mm/dd-hh:mm”格式存储日期和时间的字符串,我该如何创建提前两天的字符串?

You can use Howard Hinnant's date library.您可以使用 Howard Hinnant 的日期库。

  1. First of all, fix the input string by adding something that could be parsed as a year, and not a leap year (eg "01/" ), so that date::from_stream parses the date and time input string into a time point ( tp1 ) correctly.首先,通过添加可以解析为年份而不是闰年(例如"01/" )的内容来修复输入字符串,以便date::from_stream将日期和时间输入字符串解析为时间点( tp1 ) 正确。
  2. Get the date two days ahead of tp1 , that is, tp1 + days{2} .获取比tp1提前两天的日期,即tp1 + days{2}
  3. Format the new date back to a string by using date::format .使用date::format将新日期格式化回字符串。

[Demo] [演示]

#include <chrono>
#include <date/date.h>
#include <iostream>  // cout
#include <sstream>  // istringstream
#include <string>

std::string two_days_ahead(const std::string& dt) {
    auto fixed_dt{std::string{"01/"} + dt};
    std::istringstream iss{fixed_dt};
    date::sys_time<std::chrono::minutes> tp1{};
    date::from_stream(iss, "%y/%m/%d-%H:%M", tp1);
    return date::format("%m/%d-%H:%M", tp1 + date::days{2});
}

int main() {
    std::cout << two_days_ahead("10/30-09:50") << "\n";
}

// Input: "10/30-09:50"
// Output: 11/01-09:50

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM