Pavel Zagalsky
Pavel Zagalsky

Reputation: 1646

Extracting dates of current week using .Net?

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!

Upvotes: 0

Views: 67

Answers (2)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31203

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));

Upvotes: 3

HadiRj
HadiRj

Reputation: 1015

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));

Upvotes: 0

Related Questions