Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

datetime - How to get start of or end of week in dart

How can I get the start of or end of a week in dart? An example is if three days ago was a Monday, and today is a Wednesday, how can I find the start of the week using dart, that is on Monday

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can get the weekday from the DateTime using https://api.dart.dev/stable/2.5.1/dart-core/DateTime/weekday.html and add/subtract this number from you date:

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);

UPDATE

Please read and upvote the answer from lrn. He knows a lot more about this stuff than me. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...