Rogerto
Rogerto

Reputation: 317

How to calculate the numbered day of the week using DateTime

What is the best way to calculate the numbered day of the week over an 8 week period?

For example, my app tracks a users progress over an 8 week course.

I'm stuck on how to determine the current numbered day of the week according to the weeks progress, for example, Week 6 - Day 5

I have the users course start date as DateTime from Firebase, and can obviously get DateTime.now() to calculate the difference between course start date and now. How do I go from this so that I can display for example:

Week 2 - Day 3 or Week 6 - Day 4

Upvotes: 0

Views: 101

Answers (1)

M.mhr
M.mhr

Reputation: 1749

Let's say the course is started 15 days ago, you can get what you want by something like this:

  DateTime now = DateTime.now(); 
  DateTime start = now.subtract(Duration(days:15));

  int allDays = now.difference(start).inDays;
  int w = allDays ~/ 7 + 1;
  int d = allDays % 7;
  
  print('Week $w - day $d');

~/ is the Truncating Division Operator which gives you the Integer result of a division

Upvotes: 1

Related Questions