#include <string>
#include <cstring>
#include <iostream>
#include "time.h"
#include <ctime>
using namespace std;
//strTime格式为 20160212,size表示需减去的天数 20160212-1=20160211
string reduceTime(const std::string& strTime, int size)
{
tm tm_;
time_t t_;
std::string formatTime = strTime + " 00:00:00";
strptime(formatTime.c_str(), "%Y%m%d %H:%M:%S", &tm_);
t_ = mktime(&tm_);
t_ -= 86400 * size;
tm_ = *localtime(&t_);
char buf[128] = {0};
strftime(buf, 64, "%Y%m%d", &tm_);
return string(buf, strlen(buf));
}
//strTime格式为 20160212,size表示需加的天数 20160212+1=20160213
string addTime(const std::string& strTime, int size)
{
tm tm_;
time_t t_;
std::string formatTime = strTime + " 00:00:00";
strptime(formatTime.c_str(), "%Y%m%d %H:%M:%S", &tm_);
t_ = mktime(&tm_);
t_ += 86400 * size;
tm_ = *localtime(&t_);
char buf[128] = {0};
strftime(buf, 64, "%Y%m%d", &tm_);
return string(buf, strlen(buf));
}
/*
@settleType = 2,表示加一天
@settleType = 3,表示加到下个星期一
@settleType = 4,表示加到下个月1号
*/
std::string calcuteSettleTime(const std::string& payTime, int settleType)
{
//日结
if (settleType == 2)
{
return addTime(payTime, 1);
}
tm tstruct;
time_t t_;
std::string formatTime = payTime + " 00:00:00";
strptime(formatTime.c_str(), "%Y%m%d %H:%M:%S", &tstruct);
t_ = mktime(&tstruct);
tstruct = *localtime(&t_);
//周结
if (settleType == 3)
{
if (tstruct.tm_wday == 0)
{
tstruct.tm_wday = 7;
}
return addTime(payTime, 8 - tstruct.tm_wday);
}
//月结
if (settleType == 4)
{
tstruct.tm_mon = tstruct.tm_mon + 1;
if (tstruct.tm_mon > 11)
{
tstruct.tm_mon = 0;
tstruct.tm_year += 1;
}
tstruct.tm_mday = 1;
char buf[128] = {0};
strftime(buf, 64, "%Y%m%d", &tstruct);
return std::string(buf, strlen(buf));
}
//实时
return payTime;
}
std::string formatTime(const std::string& strTime)
{
tm tm_;
strptime(strTime.c_str(), "%Y-%m-%d %H:%M:%S", &tm_);
char buf[64] = {0};
strftime(buf, 64, "%Y%m%d", &tm_);
return std::string(buf, strlen(buf));
}
本文介绍了一种使用C++进行日期加减操作的方法,并提供了针对不同结算类型(如日结、周结、月结)计算结算日期的具体实现。通过转换字符串格式的日期,利用标准库函数实现日期的灵活调整。
981

被折叠的 条评论
为什么被折叠?



