Check if weekday is in the past DateTime c# -
i working on weather application , want when user input "tuesday" , present day wednesday, give me weather of coming tuesday instead.
any please?
there many ways "next tuesday" exact solution depends on answer question:
if today tuesday, , user types in tuesday, want today, or next week?
if answer "today", following 2 solutions work:
public static datetime nextdatebydayofweek1(dayofweek dow) { var daysuntil = ((dow - datetime.today.dayofweek) + 7) % 7; return datetime.today.adddays(daysuntil); } public static datetime nextdatebydayofweek2(dayofweek dow) { var date = datetime.today; while (date.dayofweek != dow) date = date.adddays(1); return date; }
if answer "next week", should add 1 day date use in methods:
public static datetime nextdatebydayofweek1(dayofweek dow) { var daysuntil = ((dow - datetime.today.adddays(1).dayofweek) + 7) % 7; return datetime.today.adddays(1 + daysuntil); } public static datetime nextdatebydayofweek2(dayofweek dow) { var date = datetime.today.adddays(1); while (date.dayofweek != dow) date = date.adddays(1); return date; }
you can generalize them:
public static datetime nextdatebydayofweek1(datetime startdate, dayofweek dow) { var daysuntil = ((dow - startdate.dayofweek) + 7) % 7; return startdate.adddays(daysuntil); } public static datetime nextdatebydayofweek2(datetime startdate, dayofweek dow) { var date = startdate; while (date.dayofweek != dow) date = date.adddays(1); return date; }
the startdate
returned if of correct day of week. "next week's date", use datetime.today.adddays(1)
when calling it, otherwise use datetime.today
.
why 2 solutions?
because "worst case scenario" loop-based solution 6 iterations, whereas 1 using remainder operator might need documentation understood people reads code. pros , cons.
Comments
Post a Comment