Alan wrote:
I have a InfoPath form that I need to use an event handler to perform a
calculation. The calculation is derived from a excel formula that
calculates the second tuesday of the month when the user enters the month
(numeric) and the year. Where Year and Month are variables from a dropdown
box.
=DATE(Year,Month,1+((2-(2>=WEEKDAY(DATE(Year,Month,1),2)))*7+(2-WEEKDAY(DATE(Year,Month,1),2))))
What is the best way to execute this formula in c#?
Well, not too sure of the BEST way, but:
DateTime now = DateTime.Now;
// d becomes the first day of the month
DateTime d = now.AddDays((now.Day * -1) + 1);
// Figure out if it's before or after this.
int diff = DayOfWeek.Tuesday - d.DayOfWeek;
// If it's negative, add 7 to it, otherwise
// just add it straight up.
d = d.AddDays((diff >= 0) ? diff : diff + 7);
That will work. You can trim down the code a bit by utilizing the fact that the
AddDays function returns the changed DateTime.
Chris.