Chicharito
Chicharito

Reputation: 1440

C# Datetime problem

ı need first monday future week ?

how to make C#?

now date 09.jan.2009

ı need 15.jun.2009 monday

Upvotes: 0

Views: 148

Answers (3)

codingbadger
codingbadger

Reputation: 43974

    public DateTime GetNextMonday()
    {

            DateTime dt = DateTime.Today;

            if dt.DayOfWeek == DayOfWeek.Monday
            {
                 dt.AddDays(7);
            }
            else
            {
               while (dt.DayOfWeek != DayOfWeek.Monday)
               {
                dt = dt.AddDays(1);
               }
            }
            return dt;
    }

Upvotes: 1

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31723

That should work too

DateTime monday = DateTime.Now.AddDays(-(int)DateTime.Now.DayOfWeek + 1).AddDays(7).Date

Upvotes: 3

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

If you want to get first Monday following a certain date, do this:

DateTime GetFirstMondaySince(DateTime afterWhen)
{
   int dayOfWeek = (int)someDate.DayOfWeek;
   int wantedDay = (int)DayOfWeek.Monday;
   return afterWhen.AddDays((wantedDay-dayOfWeek+7)%7);
}

For first monday of the year, use GetFirstMonday(DateTime(2009,1,1))

etc..

NOTE: untested code. Please understand and test carefully before using.

First Monday next week: GetFirstMondaySince(DateTime.Now + TimeSpan.FromDays(2));

Upvotes: 4

Related Questions