解决方案不适用于两个日期之间的天数
Solution doesn't work for number of days between two dates
我知道这个问题已经被问过几次了,我再问一次,因为我对 SO 上的现有解决方案有疑问。
我的目标是找出 1900-01-01
和给定日期之间的天数。日期格式为 yyyy-mm-dd
,类型为 std::string
.
我遵循的解决方案是
下面是我的版本:
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
也不一定 return 秒数(你假设)。
我知道这个问题已经被问过几次了,我再问一次,因为我对 SO 上的现有解决方案有疑问。
我的目标是找出 1900-01-01
和给定日期之间的天数。日期格式为 yyyy-mm-dd
,类型为 std::string
.
我遵循的解决方案是
下面是我的版本:
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
也不一定 return 秒数(你假设)。