我正在尝试创建一个功能,我可以通过调度转账,因此,我需要一个月和弱的循环选项,我面临的问题是,如果用户选择一个月的31号,每个月都没有31号,所以交易应该发生在那个特定月的结束日期。
例如:如果我开始循环日期是31 May 2022交易数量:3当前输出:交易日期=>2022年7月1日,7月31日,8月31日,正确输出:30 June 2022, 31 July 2022, 31 August 2022,
也许像我在这里提出的那样:
对于
的事情lastDayOfMonth
,您可能会做类似extension AddMonth on DateTime { DateTime addMonths([int amount = 1]) { final plusXMonths = DateTime(year, month + amount, day); final xMonthsAhead = DateTime(year, month + amount); if (xMonthsAhead.lastDayOfMonth.compareTo(plusXMonths).isNegative) { return xMonthsAhead.lastDayOfMonth; } else { return plusXMonths; } } }
这个命题基于我为之创建PR的代码:
extension DateTimeLastFirstDay on DateTime {
/// Returns the Monday of this week
DateTime get firstDayOfWeek =>
isUtc ? DateTime.utc(year, month, day + 1 - weekday) : DateTime(year, month, day + 1 - weekday);
/// Returns the Sunday of this week
DateTime get lastDayOfWeek =>
isUtc ? DateTime.utc(year, month, day + 7 - weekday) : DateTime(year, month, day + 7 - weekday);
/// Returns the first day of this month
DateTime get firstDayOfMonth => isUtc ? DateTime.utc(year, month, 1) : DateTime(year, month, 1);
/// Returns the last day of this month (considers leap years)
DateTime get lastDayOfMonth => isUtc ? DateTime.utc(year, month + 1, 0) : DateTime(year, month + 1, 0);
/// Returns the first day of this year
DateTime get firstDayOfYear => isUtc ? DateTime.utc(year, 1, 1) : DateTime(year, 1, 1);
/// Returns the last day of this year
DateTime get lastDayOfYear => isUtc ? DateTime.utc(year, 12, 31) : DateTime(year, 12, 31);
}
使用time包,您可以创建类似的代码数周。