解决方案在两个日期之间的天数内不起作用
Solution doesn't work for number of days between two dates
我知道这个问题已经被问了几次,我再问一次是因为我对 SO 的现有解决方案有问题。
我的目标是找到1900-01-01
和给定日期之间的天数。日期的格式为yyyy-mm-dd
,类型为std::string
。
我遵循的解决方案是 https://stackoverflow.com/a/14219008/2633803
以下是我的版本:
std::string numberOfDaysSince1900v2(std::string aDate)
{
string year, month, day;
year = aDate.substr(0, 4);
month = aDate.substr(5, 2);
day = aDate.substr(8, 2);
struct std::tm a = { 0,0,0,1,1,100 }; /* Jan 1, 2000 */
struct std::tm b = { 0,0,0,std::stoi(day),std::stoi(month),std::stoi(year) - 1900 };
std::time_t x = std::mktime(&a);
std::time_t y = std::mktime(&b);
double difference;
if (x != (std::time_t)(-1) && y != (std::time_t)(-1))
{
difference = std::difftime(y, x) / (60 * 60 * 24) + 36526; //36526 is number of days between 1900-01-01 and 2000-01-01
}
return std::to_string(difference);
}
它工作正常,直到给定的日期到2019-01-29
和2019-02-01
。在这两种情况下,输出都是43494
。整个 2 月,产量比预期少 3 天。然后,到了2019年3月,产量又恢复正常了。 另一种情况是2019-09-03
,输出是43710
,而期望的输出是43711
。
为什么这些特定日期会发生这种情况?我一步一步地运行解决方案,并密切关注内存中的变量,但无法解释它。
任何建议不胜感激。谢谢。
月份应表示为 0 到 11 之间的整数,而不是 1 到 12。
所以
struct std::tm a = { 0,0,0,1,0,100 }; /* Jan 1, 2000 */
struct std::tm b = { 0,0,0,std::stoi(day),std::stoi(month)-1,std::stoi(year) - 1900 };
我会说你的代码还有其他问题。您无法可靠地初始化这样的tm
(不保证结构中字段的顺序(。difftime
也不一定返回秒数(您假设(。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 线程之间的通信不起作用 - C++
- "+=" 操作在类型之间不起作用 std::复杂<double>和__complex__双精度
- 解决方案在两个日期之间的天数内不起作用
- 使用 .depends 指定 SUBDIRS 项目之间的依赖关系不起作用
- C# 和 C++ 代码之间的链接在 64 位计算机中不起作用
- ios_base::sync_with_stdio(false) 在来自标准输入的两个输入之间不起作用
- c++ 比较在缓冲区的 2 个字符串之间不起作用
- C++11 - 2 个向量之间的emplace_back不起作用
- 服务和用户模式进程之间的共享全局事件不起作用
- 为什么数组之间的==相等比较不起作用
- 为什么字符数组之间的这种比较不起作用?
- 可视化 为什么这个C++程序在某些编译器中有效,而在其他编译器中不起作用?C ++编译器之间的主要区别是什么
- C# COM-Interop dll for C++ COM dll 在 2 个解决方案之间不起作用
- 矢量元素和 txt 文件行之间的字符串比较不起作用
- 取消脱壳:删除模板角度之间的空间不起作用