Nanji Mange
Nanji Mange

Reputation: 2265

How to get the date of a given day in a specific week?

I want to get date of specific day of a given week. The week is decided by the entered date.

For example, if I want the Friday of these dates:

  1. 06/27/2018
  2. 07/04/2018
  3. 07/07/2018

I expect as outcome:

  1. 06/29/2018
  2. 07/06/2018
  3. 07/06/2018

Here, week is defined as Monday to Sunday.

Upvotes: 0

Views: 1472

Answers (4)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

A modification of the current version of DavidG's answer:

static DateTime GetDay(DateTime source, DayOfWeek dayOfWeek)
{
  const int offsetSinceMondayIsFirstDayOfWeek = 7 - (int)DayOfWeek.Monday;
  return source.AddDays(((int)dayOfWeek + offsetSinceMondayIsFirstDayOfWeek) % 7
    - ((int)source.DayOfWeek + offsetSinceMondayIsFirstDayOfWeek) % 7);
}

This takes into account that the asker considers Monday to be the first day of the week. If you want Saturday as the first day of week, just replace Monday with Saturday above.

In the special case where you consider Sunday the first day of the week, it reduces to DavidG's original method:

static DateTime GetDay(DateTime source, DayOfWeek dayOfWeek)
{
  return source.AddDays((int)dayOfWeek - (int)source.DayOfWeek);
}

because the DayOfWeek enum type of the BCL already "wraps around" between Saturday (= 6) and Sunday (= 0).


On http://chartsbin.com/view/41671 there is a world map that apparently shows what day of week is considered the first day of the week in different regions.

Upvotes: 2

DavidG
DavidG

Reputation: 118937

You can do this with some clever maths based on the DayOfWeek:

public DateTime GetDay(DateTime source, DayOfWeek dayOfWeek, 
    DayOfWeek weekStartsOn = DayOfWeek.Monday)
{
    var offset = (int)source.DayOfWeek - (int)weekStartsOn;;
    if(offset < 0)
    {
        offset = offset + 7;
    }
    return source.AddDays(-offset + (int)dayOfWeek - (int)weekStartsOn);
}

And use it like this:

var someDate = ...; //Get a date from somewhere

var friday = GetDay(someDate, DayOfWeek.Friday);
var monday = GetDay(someDate, DayOfWeek.Monday);

And if your week starts on a Sunday, just use the optional third parameter, for example:

var friday = GetDay(someDate, DayOfWeek.Friday, DayOfWeek.Sunday);

Upvotes: 4

D3ivid
D3ivid

Reputation: 61

    public void TestMethod1 ( )
    {

        DateTime date = DateTime.Now;
        DateTime friday = date.AddDays( (int)DayOfWeek.Friday - (int)date.DayOfWeek );
        Console.WriteLine( friday.ToString( ) );

    }

Upvotes: 0

curdev
curdev

Reputation: 38

   using System;
      using System.Globalization;

   public class Example
   {
      public static void Main()
      {
         DateTime dateValue = new DateTime(2008, 6, 11);
         Console.WriteLine(dateValue.ToString("ddd", 
                           new CultureInfo("fr-FR")));    
      }
   }

Upvotes: -4

Related Questions