如何获得 Dart 一周的开始或结束?例如,如果三天前是星期一,今天是星期三,我如何使用 Dart 找到一周的开始,也就是星期一
最佳答案
您可以使用https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html从DateTime中获取工作日,并从日期中添加/减去该数字:
代码语言:javascript复制void main() {
final date = DateTime.parse('2019-10-08 15:43:03.887');
print('Date: $date');
print('Start of week: ${getDate(date.subtract(Duration(days: date.weekday - 1)))}');
print('End of week: ${getDate(date.add(Duration(days: DateTime.daysPerWeek - date.weekday)))}');
}
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);