Kadir
Kadir

Reputation: 3224

Get datetime from given day

user just enter the day of week. For instance user enter friday. I need to find the exact date of given day and format will be like dd.MM.yyyy. But I don't know how I do it.
Example:

label1 - Friday (entered by user)
label2 - 08.06.2012 (found by system)

label1 is just a string (just Friday). It's coming from webservice as a string variable. I need to find the date and compare with today, If it's not equal or small than today I give date of upcoming Friday, else I give the date of the Friday the week after.

Upvotes: 1

Views: 807

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

"If it's not equal or small than today I give exact date, else I give next week date. "

Assuming that means that you return always the next date in future with the given day of week, the only exception is when today is the given day of week.

public static DateTime getNextWeekDaysDate(String englWeekDate)
{
    var desired = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), englWeekDate);
    var current = DateTime.Today.DayOfWeek;
    int c = (int)current;
    int d = (int)desired;
    int n = (7 - c + d);

    return DateTime.Today.AddDays((n >= 7) ? n % 7 : n);
}

Let's test:

DateTime Monday   = getNextWeekDaysDate("Monday");    // 2012-06-11
DateTime Tuesday  = getNextWeekDaysDate("Tuesday");   // 2012-06-05  <-- !!! today
DateTime Wednesday= getNextWeekDaysDate("Wednesday"); // 2012-06-06
DateTime Thursday = getNextWeekDaysDate("Thursday");  // 2012-06-07
DateTime Friday   = getNextWeekDaysDate("Friday");    // 2012-06-08

Upvotes: 2

GameAlchemist
GameAlchemist

Reputation: 19294

get current time with DateTime.now
Current day is DateTime.Now.DayOfWeek
Then get the day of week your user entered
Then your result is DateTime.now.AddDays( NowDayOfWeek - UserDayOfWeek).

Upvotes: 0

m03geek
m03geek

Reputation: 2538

  1. Create enum of days (i.e. monday - 0, tuesday - 1, etc);
  2. Get DateTime.Now DayOfWeek and cast in some way it to your enum value.
  3. Calculate difference between Now.DayOfWeek and user's day of the week;
  4. Use DateTime.AddDays(difference).DayofTheWeek;

Upvotes: 0

Related Questions