Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Time Period in weeks between 2 dates

Tags:

c#

I have a web application where the user will input 2 dates. A StartDate and an EndDate. Now I want to write it so that when StartDate and EndDate is selected to determine how many weeks there are and then to display the dates of those weeks for example if the user selects 01-11-2018 as the StartDate and 31-12-2018 as the EndDate then I want to display the following and keep in mind the Weeks are just for reference as to how it is going to look:

  1. Week 98 : 01 November 2018 - 03 November 2018
  2. Week 99 : 04 November 2018 - 10 November 2018
  3. Week 100 : 11 November 2018 - 17 November 2018

I already have the amount of weeks by using this previous post.

Now I just want to be able to to display each individual weeks Start and End date in all the weeks. I tried creating a list with the weeks and then using a Foreach to check the weeks added but this is not quite right. I am just searching for the most efficient way of accomplishing this goal.

Links also checked with similar problems are : Link1

like image 828
Ruben Redman Avatar asked Jan 22 '26 22:01

Ruben Redman


1 Answers

I have made this snippet... not sure if everything is up to spec:

var startDate = new DateTime(2018, 11, 1);
var endDate = new DateTime(2018, 12, 31);

int diff = (7 + (startDate.DayOfWeek - DayOfWeek.Monday)) % 7;
var weekStartDate = startDate.AddDays(-1 * diff).Date;
var i = 1;
var weekEndDate = DateTime.MinValue;    
while(weekEndDate < endDate) {
    weekEndDate = weekStartDate.AddDays(6);
    var shownStartDate = weekStartDate < startDate ? startDate : weekStartDate;
    var shownEndDate = weekEndDate > endDate ? endDate : weekEndDate;
    Console.WriteLine($"Week {i++}: {shownStartDate:dd MMMM yyyy} - {shownEndDate:dd MMMM yyyy}");
    weekStartDate = weekStartDate.AddDays(7);
}

This assumes your weeks are "counting", starting on the week the start date is in, and uses monday as the first day of week and sunday as the last one (the ranges you see are monday - sunday except for the first/last week, which would use the start/end date instead if it doesn't happen to be monday or sunday)

You can run it online here: https://dotnetfiddle.net/jJ4Ydu

If you also need to know which week of the year it is, then it depends if you want the .NET style or the ISO8601 style... the typical one is the latter, and you can use, for example, the method found on this answer, so it'd look something like: https://dotnetfiddle.net/oJscjF

Notice how Dec-31st-2018 (which is monday) is the week 1 of 2019 on ISO8601, but week 53 for .NET

like image 200
Jcl Avatar answered Jan 24 '26 17:01

Jcl