tags:

views:

446

answers:

5

How can i learn next wednesday, monday in a week? Forexample Today 06.02.2009 next Monday 09.02.2009 or wednesday 11.02.2009 there is any algorithm?

i need :

which day monday in comingweek?

findDay("Monday")

it must return 09.02.2009

=====================================================

findDay("Tuesday")

it must return 10.02.2009

A: 

Maybe this is a good place to start:

http://www.java2s.com/Tutorial/CSharp/0260__Date-Time/0020__DateTime.htm

Andrew Hare
+3  A: 
DateTime now = DateTime.Now;
DateTime nextMonday = now.AddDays((int)now.DayOfWeek - (int)DayOfWeek.Monday);

Hum it seems that I answered too quickly. Actually there are more checking to do. Have a look at nobugz or peterchen answers.

Tyalis
Umm... wouldn't that subtract one or more days in most cases?
peterchen
Thanks Alot it is great!!!!
Phsika
You were right peterchen, thanks.
Tyalis
+5  A: 
public static DateTime GetNextDayDate(DayOfWeek day) {
  DateTime now = DateTime.Now;
  int dayDiff = (int)(now.DayOfWeek - day);
  if (dayDiff <= 0) dayDiff += 7;
  return now.AddDays(dayDiff);
}
Hans Passant
You should add sample usage of this function to this excellent answer to make it complete. Just a tip! ;-)
Cerebrus
This would make a great extension method. +1
Mike Hofer
I get incorrect results with this. It should be (day - now.DayOfWeek) rather than the other way round.
darasd
A: 

Like Tyalis, but some extra checking is required:

int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek;
if (daysUntilMonday <= 0) 
  daysUntilMonday += 7;

Monday = DateTime.Now.AddDays(daysUntilMonday);
peterchen
A: 

Just iterate a bit:

DateTime baseDate = ...;
DayOfWeek requiredDayOfWeek = ...;

while(baseDate.DayOfWeek != requiredDayOfWeek)
    baseDate = baseDate.AddDays(1);

You can also write an extension method if those are available:

static Next(this DateTime date, DayOfWeek requiredDayOfWeek) { ... }

and you'll get pretty syntax: today.Next(DayOfWeek.Saturday).

Anton Gogolev