gpt4 book ai didi

flutter - Dart:如何查找两个日期之间的天数(周末或谓词除外)

转载 作者:行者123 更新时间:2023-12-03 04:26:19 27 4
gpt4 key购买 nike

我需要计算Dart中两个日期之间的天数。
有内置的功能。

 leaveEndDate.difference(leaveStartDate).inDays

但我不希望包括周末。
我有什么办法可以在这两个日期之间穿梭,还是可以排除周末。

最佳答案

我认为您别无选择,只能遍历整天检查这是否是周末:

void main() {
DateTime date1 = DateTime(2019, 12, 01);
DateTime date2 = DateTime(2019, 12, 31);

print(getDifferenceWithoutWeekends(date1, date2));
}

int getDifferenceWithoutWeekends(DateTime startDate, DateTime endDate) {
int nbDays = 0;
DateTime currentDay = startDate;
while (currentDay.isBefore(endDate)) {
currentDay = currentDay.add(Duration(days: 1));
if (currentDay.weekday != DateTime.saturday && currentDay.weekday != DateTime.sunday) {
nbDays += 1;
}
}
return nbDays;
}

结果:

22



编辑:

另一种解决方案(不确定是否更快),但是在需要标识日期时会很有用(可以返回 list<DateTime>而不是 List<int>来查看哪一天是周末)。

在这里,我在2个日期之间建立每一天,如果不是周末,则返回1,然后对列表求和:

void main() {
DateTime startDate = DateTime(2019, 12, 01);
DateTime endDate = DateTime(2019, 12, 31);

int nbDays = endDate.difference(startDate).inDays + 1;

List<int> days = List.generate(nbDays, (index) {
int weekDay = DateTime(startDate.year, startDate.month, startDate.day + (index)).weekday;
if (weekDay != DateTime.saturday && weekDay != DateTime.sunday) {
return 1;
}
return 0;
});

print(days.reduce((a, b) => a + b));
}

关于flutter - Dart:如何查找两个日期之间的天数(周末或谓词除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529122/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com