Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k 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 Reply

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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...