tags:

views:

10610

answers:

14

How do I find the Start of the week (Both Sunday and Monday) knowing just the current time in C#.NET

Something like:

DateTime.Now.StartWeek(Monday);
+3  A: 

This would give you the preceding Sunday (I think):

  DateTime t = DateTime.Now;
  t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);

Skizz

Skizz
A: 

The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday:

private DateTime getStartOfWeek(bool useSunday)
{
    DateTime now = DateTime.Now;
    int dayOfWeek = (int)now.DayOfWeek;

    if(!useSunday)
        dayOfWeek--;

    if(dayOfWeek < 0)
    {// day of week is Sunday and we want to use Monday as the start of the week
 // Sunday is now the seventh day of the week
        dayOfWeek = 6;
    }

    return now.AddDays(-1 * (double)dayOfWeek);
}
firedfly
+2  A: 

This may be a bit of a hack, but you can cast the .DayOfWeek property to an int (it's an enum and since its not had its underlying data type changed it defaults to int) and use that to determine the previous start of the week.

It appears the week specified in the DayOfWeek enum starts on Sunday, so if we subtract 1 from this value that'll be equal to how many days the Monday is before the current date. We also need to map the Sunday (0) to equal 7 so given 1 - 7 = -6 the Sunday will map to the previous Monday:-

DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
DateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek);

The code for the previous Sunday is simpler as we don't have to make this adjustment:-

DateTime now = DateTime.Now;
int dayOfWeek = (int)now.DayOfWeek;
DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);
kronoz
+29  A: 

An extension method? They're the answer to everything you know! ;)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
     int diff = dt.DayOfWeek - startOfWeek;
     if (diff < 0)
     {
      diff += 7;
     }

     return dt.AddDays(-1 * diff).Date;
    }
}

Which is used thusly:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
Sarcastic
+23  A: 

A little more verbose and culture-aware:

System.Globalization.CultureInfo ci = 
    System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
DayOfWeek today = DateTime.Now.DayOfWeek;
DateTime sow = DateTime.Now.AddDays(-(today - fdow)).Date;
Jason Navarrete
got an error with this: today = SUNDAY; fdow = MONDAY; (today - fdow) == -1; DateTime.Now.AddDays(-(-1)).Date == DateTime.Now.AddDays(+1).Date; 01-02-2010 != 25-01-2010 !!
balexandre
A: 
DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, t.Hour, t.Minute, t.Second);

Would give you midnight on the 1st Sunday of the week,

DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek - 1, t.Hour, t.Minute, t.Second);

gives you the 1st Monday at midnight

Glenn Slaven
A: 

I have a static class that does all this for me. Here's the week part:

#region Weeks
 public static DateTime GetStartOfLastWeek()
 {
  int DaysToSubtract = (int)DateTime.Now.DayOfWeek + 7;
  DateTime dt = DateTime.Now.Subtract( TimeSpan.FromDays( DaysToSubtract ) );
  return new DateTime( dt.Year, dt.Month, dt.Day, 0, 0, 0, 0 );
 }

 public static DateTime GetEndOfLastWeek()
 {
  DateTime dt = GetStartOfLastWeek().AddDays( 6 );
  return new DateTime( dt.Year, dt.Month, dt.Day, 23, 59, 59, 999 );
 }

 public static DateTime GetStartOfCurrentWeek()
 {
  int DaysToSubtract = (int)DateTime.Now.DayOfWeek;
  DateTime dt = DateTime.Now.Subtract( TimeSpan.FromDays( DaysToSubtract ) );
  return new DateTime( dt.Year, dt.Month, dt.Day, 0, 0, 0, 0 );
 }

 public static DateTime GetEndOfCurrentWeek()
 {
  DateTime dt = GetStartOfCurrentWeek().AddDays( 6 );
  return new DateTime( dt.Year, dt.Month, dt.Day, 23, 59, 59, 999 );
 }
 #endregion

I have methods for all these Date operations in the very same class, same for months, years, days, quarters, etc. hope it helps you.

Martín Marconcini
A: 

You could use the excellent Umbrella library:

using nVentive.Umbrella.Extensions.Calendar;
DateTime beginning = DateTime.Now.BeginningOfWeek();

However, they do seem to have stored Monday as the first day of the week (see the property nVentive.Umbrella.Extensions.Calendar.DefaultDateTimeCalendarExtensions.WeekBeginsOn), so that previous localized solution is a bit better. Unfortunate.

Edit: looking closer at the question, it looks like Umbrella might actually work for that too:

// Or DateTime.Now.PreviousDay(DayOfWeek.Monday)
DateTime monday = DateTime.Now.PreviousMonday(); 
DateTime sunday = DateTime.Now.PreviousSunday();

Although it's worth noting that if you ask for the previous Monday on a Monday, it'll give you seven days back. But this is also true if you use BeginningOfWeek, which seems like a bug :(.

Domenic
+6  A: 

Let's combine the culture-safe answer and the extension method answer:

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
        DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
        return DateTime.Today.AddDays(-(DateTime.Today.DayOfWeek- fdow));
    }
}
Joel Coehoorn
An extension method that takes a date parameter and returns the first day of the current week? Cool!
neither dt nor startOfWeek is used within your function, I guess the first one should be used instead of DateTime.Today
phq
+1 phq's comment
Matt Frear
A: 

@Sarcastic Thanks for the excellent and elegant answer which meets my needs exactly :)

GateKiller
+2  A: 

using Fluent DateTime http://fluentdatetime.codeplex.com/

        var monday = DateTime.Now.Previous(DayOfWeek.Monday);
        var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);
Simon
I'd hate to take on a dependency just for this. "Know your dependencies and kill them" seems to come to mind. :)
Esteban Araya
A: 

public static System.DateTime getstartweek() { System.DateTime dt = System.DateTime.Now; System.DayOfWeek dmon = System.DayOfWeek.Monday; int span = dt.DayOfWeek - dmon; dt = dt.AddDays(-span); return dt; }

mails2008
A: 

Thanks for the examples. I needed to always use the "CurrentCulture" first day of the week and for an array I needed to know the exact Daynumber.. so here are my first extensions:

public static class DateTimeExtensions
{
    //http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
    //http://stackoverflow.com/questions/1788508/calculate-date-with-monday-as-dayofweek1
    public static DateTime StartOfWeek(this DateTime dt)
    {
        //difference in days
        int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.

        //As a result we need to have day 0,1,2,3,4,5,6 
        if (diff < 0)
        {
            diff += 7;
        }
        return dt.AddDays(-1 * diff).Date;
    }

    public static int DayNoOfWeek(this DateTime dt)
    {
        //difference in days
        int diff = (int)dt.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; //sunday=always0, monday=always1, etc.

        //As a result we need to have day 0,1,2,3,4,5,6 
        if (diff < 0)
        {
            diff += 7;
        }
        return diff + 1; //Make it 1..7
    }
}
A: 

I have posted the complte code for calculating the begin/end of week, month, quarter and year on my blog zamirsblog.blogspot.com

Zamir