如何从structtm中减去一天,同时确保完整性
How to subtract a day from struct tm but ensuring integrity?
如何在确保新日期有效的同时从structtm中减去一天。
例如,
struct tm time = {};
time.tm_year = year - 1900;
time.tm_mon = month - 1;
time.tm_mday = day;
天=1,月=9,年=2014。
所以,如果我现在减去一天的时间.tm_mday=0,这是无效的
但我不能只将tm_mday设置为31并将月份减少1,因为我不知道在运行时场景中前一个月有多少天。
我使用了这里的代码:从日期中添加或减去天数的算法?正如@tenfour在上面的评论中所建议的那样。
在这里添加我的代码,以供下一步寻找此代码的人快速参考。
struct tm time = {};
time.tm_year = year - 1900;
time.tm_mon = month - 1;
time.tm_mday = day;
if(subtractDay)
{
AddDays(&time, -1);
}
void AddDays(struct tm* dateAndTime, const int daysToAdd) const
{
const time_t oneDay = 24 * 60 * 60;
// Seconds since start of epoch --> 01/01/1970 at 00:00hrs
time_t date_seconds = mktime(dateAndTime) + (daysToAdd * oneDay);
*dateAndTime = *localtime(&date_seconds);
}
相关文章:
- 如何确保C++函数在定义之前声明(如override关键字)
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 使用Unique_ptr确保工厂中的对象唯一
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 确保流程关闭
- 如何确保接受的C++模板类型使运算符重载?
- 确保编译时的特定 std::array 位置
- C++ 确保子类为常量提供自定义值
- 确保内存映射页位于内存中
- 确保套装新鲜度的有效方法
- C ++类型特征:确保子类实现方法
- 是否确保 2 个连续的 std::chrono::steady_clock::now() 不相等?
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- 确保无变体的型号安全
- 确保特征将 AVX 矢量化用于特定操作
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 如何确保 Visual C++ 不允许作用域枚举访问?
- 如何确保调用显式构造函数并允许大括号初始化?
- 如何从structtm中减去一天,同时确保完整性