0

I am trying to extract dates for current week's days and I just can't find a sensible, smart way instead of a long case, switches and if statements. Anybody knows a relatively easy way to extract those using .Net? Thanks!

Pavel Zagalsky
  • 1,620
  • 7
  • 22
  • 52
  • 1
    Show what did you tried and why you search for another aproach – Fabio Jun 07 '15 at 09:47
  • Haven't started yet, I have a mental image of cycling through every day and adding or substracting days according to the "Today" value. I just hope there's a more reasonable approach – Pavel Zagalsky Jun 07 '15 at 09:50
  • Try `DateTime.Now.DayOfWeek` and then based on the result count another dates of the same week – Fabio Jun 07 '15 at 09:52
  • The concept of "week" is a fuzzy concept due to the fact that many cultures have different notions about when the week starts. Could you clarify if this is for a particular culture or whether you need a culture-independent solution? For instance, are you making a general purpose class library or are you making an application that will only have to handle Israeli weeks? – Lasse V. Karlsen Jun 07 '15 at 10:43
  • I need the Israeli one that starts on Sunday and ends on Saturday – Pavel Zagalsky Jun 07 '15 at 13:41

2 Answers2

3

The DateTime.DayOfWeek is an enumeration that starts with Sunday being 0 and going forward. If you take today's day-of-week, it will also tell how many days ago Sunday was. Therefore going back that many days will give you the Sunday of this week, assuming week starts on Sunday. You can go forward from that for the seven days of the week.

var today = DateTime.Now;
var thisSunday = today.AddDays(-(int)today.DayOfWeek);

for (int i=0; i<7; i++)
  Console.WriteLine(thisSunday.AddDays(i).ToString());

If the week starts from Monday, use

var thisMonday = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
0

You may use extension method to set the day that week start with (credit goes to @Compile This)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime datetime, DayOfWeek startOfWeek)
    {
        int difference = datetime.DayOfWeek - startOfWeek;
        if (difference >= 0)
            return datetime.AddDays(-1 * difference).Date;
        difference += 7;
        return datetime.AddDays(-1 * difference).Date;
    }
}

Then you can get date of the week using same loop as @Sami_Kuhmonen mentioned:

        DateTime d = DateTime.Now.StartOfWeek(DayOfWeek.Saturday);
        for (int i = 0; i < 7; i++)
            Console.WriteLine(d.AddDays(i));
Community
  • 1
  • 1
HadiRj
  • 1,015
  • 3
  • 21
  • 41