产品需求:获取最近1个月、3个月、半年、1年的交易记录。
最快方式:直接用个30天、60天、180天、365天的Duration,用DateTime相见即可。
存在问题:实际上是不准确的,例如3月1号的最近1个月,应该是2月1-3月1,但是2月如果只有28天,会算成1月30号开始;
优化目标:
- 往前X个月,需要根据前X个月每个月天数相加为准,不是一成不变的30*n;
- 如往前X个月没有当前天则返回前x月+1个月的1号(例如3月30往前1个月,没有2月30,则返回3月1号)
百度了下没有现成的,自己写了下,给大家参考参考吧。上代码:
///计算某个时间往前X个月的具体日期
///beforeMonth 月数 例如1、3、5、12(1年)、36(3年)
///anchorDateTime 锚定日期,比如2022-7-6
///如往前X个月没有有当前天则返回前x月+1个月的1号(例如3月30往前1个月,没有2月30,则返回3月1号)
static int getBeforeMonthTotalDays(int beforeMonth, DateTime anchorDateTime) {
DateTime startTime;
//1--先计算目标年月
if (anchorDateTime.month <= beforeMonth) {//月份不足,计算年份
int year = anchorDateTime.year - beforeMonth ~/ 12; //计算年数
int month =beforeMonth ~/ 12 * 12 + anchorDateTime.month - beforeMonth; //计算月份
if (month == 0) {//0月改为上一年的12月
year -=1;
month = 12;
}
startTime