I have a function which takes two DateTime parameters and I have to add separate offsets to these date. I know that DateTime has a AddDays function to add days to a date and it throws an exception if DateTime is less than MinValue or greater than MaxValue.
Now I want to do a safe check whether adding/subtracting the following number of days to a DateTime can cause over/under flow or not.
safeStartDate = (startDate == DateTime.MinValue || startDate == DateTime.MaxValue) ? startDate : startDate.AddDays(startDateOffset);
safeEndDate = (endDate == DateTime.MaxValue || endDate == DateTime.MinValue) ? endDate : endDate.AddDays(enDateOffset);
By doing this, I am making it one level exception free but date can be DateTime.Max - 1 and while trying to add offset it throws an exception. I am looking a better way that whether the final values over/under flows without doing the actual calculation, in order to prevent exception.
If catch is not called very often you can do:
try
{
safeDate = dt.AddDays(days);
}
catch (ArgumentOutOfRangeException)
{
safeDate = date;
}
Alternatively,
var maxDays = (DateTime.MaxValue - dt).TotalDays;
safeDate = (days <= maxDays) ? dt.AddDays(days) : dt;
Or if there are negative days:
var maxDays = (DateTime.MaxValue - dt).TotalDays;
var minDays = (DateTime.MinValue - dt).TotalDays;
return (minDays <= days && days <= maxDays) ? dt.AddDays(days) : dt;
Or just use the method from Rawling's answer: CanAddDays(dt, days) ? dt.AddDays(days) : dt
The try/catch version is about 25% faster if you don't catch and about 1000x slower if you do. So, if you expected to catch more than about 1 time in every 5000 uses, then use the second version.
You can use the following to check whether you can add a given number of days to a given DateTime without causing an overflow:
bool CanAddDays(DateTime dt, int days)
{
double maxDaysToAdd = (DateTime.MaxValue - dt).TotalDays;
double minDaysToAdd = (DateTime.MinValue - dt).TotalDays;
return days <= maxDaysToAdd && days >= minDaysToAdd;
}
You might consider the following method:
private static DateTime AddDays(DateTime dateTime, int days)
{
var daysTimeSpanTicks = (new TimeSpan(days, 0, 0, 0)).Ticks;
return (days >= 0) ?
(DateTime.MaxValue.Ticks < dateTime.Ticks + daysTimeSpanTicks) ? dateTime : dateTime.AddDays(days) :
(dateTime.Ticks + daysTimeSpanTicks < 0) ? dateTime : dateTime.AddDays(days);
}
A sample usage is:
DateTime date = DateTime.MinValue;
DateTime safe = AddDays(date, -100);
I guess you are looking for something like this
DateTime Now = DateTime.Now;
DateTime Max = DateTime.MaxValue;
Max.Subtract(Now);
int DaysToAdd = 1000;//or something else
if (Max.Day > DaysToAdd) Now.AddDays(DaysToAdd);//add
Related
I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate and EndDate are of type DateTime.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
In case someone wants numer of whole days as a double (a, b of type DateTime):
(a.Date - b.Date).TotalDays
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.
If you want the duration in days to include fractions of days, then as already suggested
use (EndDate - StartDate).TotalDays.
If you want the duration to reflect
the distance between two days, then use (EndDate.Date - StartDate.Date).Days
If you want the duration to reflect the
duration between the morning of the start date, and the evening of
the end date (what you typically see in project management software), then use
(EndDate.Date - StartDate.Date).Days + 1
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Using a timespan would solve the problems as it has many attributes:
DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();
For a and b as two DateTime types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:
int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);
This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).
If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.
On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.
Happy coding! ^_^
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Get the difference between the two dates and then get the days from:
int total_days = (EndDate - StartDate).TotalDays
try this truly worked Get actual days diff. date format is "dd/MM/yyyy"
string[] d1 = txtFromDate.Values.Split('/');
string[] d2 = txtToDate.Values.Split('/');
DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));
TimeSpan TDiff = ToDt.Subtract(FrmDt);
String DaysDiff = TDiff.TotalDays.ToString();
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}
Ok, so I have a date stored in UK format (dd/mm/yy) which I need to display in the locale of wherever the user might be.
The issue is that this date can be 000000 (00/00/2000); so I can't convert it to DateTime directly, as DateTime doesn't support 0 values for day or month.
I have this so far:
int dateInt = ddmmyy;
var year = (dateInt % 100) + 2000;
var month = (dateInt / 100) % 100;
var day = (dateInt / 100000);
var result = new DateTime(year, month, day); //2014/00/00 at this point, so breaks.
var resultStr = result.ToString(CultureInfo.InvariantCulture);
return resultStr;
What's the correct way to add support for 0 values initially? I've tried changing the 0 to 1 before converting to DateTime, running the conversion and then replacing with a 0 again; but due to culture variants I see no way that this method can support other cultures, which is the purpose of this conversion to begin with.
Any ideas? I'm guessing this is a common issue.
Is this what you need ?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] savedDates = new int[] { 000000, 010000, 000013 };
foreach (var item in savedDates)
{
DateTime date = ConvertToDate(item);
Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());
}
Console.ReadLine();
}
private static DateTime ConvertToDate(int item)
{
string temp = item.ToString("D6");
int day = int.Parse(temp.Substring(0, 2));
int month = int.Parse(temp.Substring(2, 2));
int year = int.Parse(temp.Substring(4, 2));
if (day == 0)
day = 1;
if (month == 0)
month = 1;
year += 2000;
return new DateTime(year, month, day);
}
}
}
I would not store dates like this as the methodology for doing so is already provided by the .NET framework.
The best way to store dates would be to use Culture.InvariantCulture for string conversion cases and then convert to local culture for display purposes as necessary. DateTime itself is culture-independent so converting between cultures is very easy.
can anyone help me with the formatting of the following?
if(system.datetime.now > 20:00:00 AND < 23:59:59)
NewDateTime = (system.datetime.now + 1 day) + time as 00:01:00
ie if the sysdate meets the criteria, make NewDateTime = Sysdate + 1 day, with the time as 00:01:00
thanks
You shouldn't be dealing with formatting at all here. I suspect you want something like:
TimeSpan earliest = new TimeSpan(20, 0, 0);
TimeSpan latest = new TimeSpan(23, 59, 59);
DateTime now = DateTime.Now;
TimeSpan currentTime = now.TimeOfDay;
if (currentTime > earliest && currentTime < latest)
{
DateTime newDateTime = now.Date.AddDays(1).AddHours(1);
}
One important point here is that I'm only taking DateTime.Now once, rather than every time we're interested in "the current time". That leads to better consistency.
I'd also question your "latest" part - do you really want the behaviour to be different at 23:59:59.5? Don't you really mean "any time after 8pm"? And possibly that should be inclusive, too? That would lead to:
// Probably make this a static readonly field
TimeSpan earliest = new TimeSpan(20, 0, 0);
DateTime now = DateTime.Now;
TimeSpan currentTime = now.TimeOfDay;
if (currentTime >= earliest)
{
DateTime newDateTime = now.Date.AddDays(1).AddHours(1);
}
DateTime now = DateTime.Now;
DateTime newDateTime;
if (now.Hours >= 20)
{
newDateTime = now.Date.AddDays(1).AddHours(1);
}
Roughly this is what I think you want:
CurrentTime=DateTime.Now;
if(CurrentTime.GetHour()>19)
{
NewDateTime=CurrentTime.AddDays(1);
NewDateTime.SetHour(1);
NewDateTime.SetMinute(0);
NewDateTime.SetSecond(0);
}
I think you can do that - if not you can calculate the time based on the current time
NewDateTime.AddHours(-CurrentTime.Hour-1)
NewDateTime.AddMinutes(-CurrentTime.Minute);
Your code is not valid in many aspects:
if(system.datetime.now > 20:00:00 AND < 23:59:59)
In C#, there is no "between" operator, so you need two comparisons plus the AND:
if(system.datetime.now > 20:00:00 AND system.datetime.now < 23:59:59)
It is && (for or, it is ||)
if(system.datetime.now > 20:00:00 && system.datetime.now < 23:59:59)
Note that && and || have short-circuit behaviour, that is, if the left operand of && if false, the right operand is not evaluated. Same for ||, except that if the left hand operand is true, the right hand operand is not evaluated.
C# does not have time literals. Now it depends on what exactly you want to compare. Do you intend to see whether it is 20 o'clock already? Then do (note that DateTime.Now also contains today's date, DateTime.Today is the beginning of the current day):
if(system.datetime.now > system.datetime.today.addHours (20)
&& system.datetime.now < system.datetime.today.addDays (1))
C# source code is case sensitive, so
if(System.DateTime.Now > System.Datetime.Today.AddHours (20)
&& System.DateTime.Now < System.DateTime.Today.AddDays (1))
You could also work with TimeSpans, which comes in handy when you also want to specify minutes and seconds (assume 20:15 for example):
if(System.DateTime.Now > System.Datetime.Today.Add (new TimeSpan(20,15,0))
&& System.DateTime.Now < System.DateTime.Today.AddDays (1))
I'd advise to use a named value, though:
var tomorrow = System.DateTime.Today.AddDays(1);
var quincyTime = today.Add (new TimeSpan (20,15,0));
if(System.DateTime.Now > quincyTime && System.DateTime.Now < tomorrow)
Further, which is important, Now gives you (roughly) the moment when you call it. So if you have multiple invocations of Now, store it so it doesn't change throughout the execution of your function:
var now = System.DateTime.Now;
var today = System.DateTime.Today;
var quincyTime = today.Add (new TimeSpan (20,15,0));
var tomorrow = today.AddDays(1);
if(now > quincyTime && now < tomorrow)
The observing reader might recognize that not even Today might be save if this program runs in a nuclear power plant at midnight. There is cure:
var now = System.DateTime.Now;
var today = now.Date;
Also note that the if-body is either a single statement, e.g.
if(now > quincyTime && now < tomorrow)
; // empty statement
if(now > quincyTime && now < tomorrow)
foobar();
or a whole "block":
if(now > quincyTime && now < tomorrow)
{
} // empty block
if(now > quincyTime && now < tomorrow)
{
foobar();
frob();
}
Btw, if you meant "at least"/"at max" instead of "later"/"sooner", use <= and >=:
if(now >= quincyTime && now <= tomorrow) {...}
how to find whether the sunday falls between two dates.if sunday exist subtract one days from the difference between two days
If I understand correctly, you are looking for something like this:
public static bool DoesIncludeSunday(DateTime startDate, DateTime endDate)
{
bool r = false;
TimeSpan testSpan = new TimeSpan(6, 0, 0, 0);
TimeSpan actualSpan =endDate - startDate;
if (actualSpan >= testSpan) { r = true; }
else
{
DateTime checkDate = endDate;
while (checkDate > startDate)
{
r = (checkDate.DayOfWeek == DayOfWeek.Sunday);
if(r) { break; }
checkDate = checkDate.AddDays(-1);
}
}
return r;
}
The endDate needs to be the most recent date. The first part simply keeps us from checking if the start and end dates are more than 6 days apart (it will include a sunday, so no need to continue). The second bit just walks backward one day at a time from the endDate checking if Sunday is in there.
Once you know if sunday is part of the span, you can make whatever changes to the dates you want from the calling code.
Just because I like to be clever, I wrote it up this way:
public static int DaysExcludingSundays(DateTime start, DateTime end)
{
return ((end - start).Days + 1) - ((((end - start).Days + 1) + (((int)start.DayOfWeek + 6) % 7)) / 7);
}
Feel free to copy and paste this code without understanding what it means. I enjoyed the puzzle.
Broken down:
int startOffset = ((int) start.DayOfWeek + 6) % 7;
int totalInclusiveDays = (end - start).Days + 1;
int numberOfSundays = (totalInclusiveDays + startOffset) / 7;
int numberOfDaysWithoutSundays = totalInclusiveDays - numberOfSundays;
Here is what I am trying to do:
Given a date, a day of the week, and an integer n, determine whether the date is the nth day of the month.
For example:
input of 1/1/2009,Monday,2
would be false because 1/1/2009 is not the second Monday
input of
11/13/2008,Thursday,2
would return true because it is the second Thursday
How can I improve this implementation?
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
int d = date.Day;
return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}
You could change the check of the week so the function would read:
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
Other than that, it looks pretty good and efficient.
The answer is from this website. Copy/pasted here in case that site is ever lost.
public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week)
{
// validate month value
if(month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("Invalid month value.");
}
// validate the nth value
if(nth < 0 || nth > 5)
{
throw new ArgumentOutOfRangeException("Invalid nth value.");
}
// start from the first day of the month
DateTime dt = new DateTime(year, month, 1);
// loop until we find our first match day of the week
while(dt.DayOfWeek != day_of_the_week)
{
dt = dt.AddDays(1);
}
if(dt.Month != month)
{
// we skip to the next month, we throw an exception
throw new ArgumentOutOfRangeException(string.Format("The given month has less than {0} {1}s", nth, day_of_the_week));
}
// Complete the gap to the nth week
dt = dt.AddDays((nth - 1) * 7);
return dt;
}
Here is what the MSDN have to say. Its VB, but it translates easily.
It looks like the language supplies date/day methods for a given date. If anybody was interested you can read about Zeller's congruence.
I don't think that's what they wanted you to do but you could find the day of week of the first day of a month from that. Now that I thought about it you could find the day of week for the given day as N and get that modulo 7.
Oh wait, is that the Nth occurance of a day of the week (like Sunday) or like the Nth weekday of the month! Okay I see the examples.
Maybe it would make a difference if you could construct a date such as the 1st of a month..
Given that it is Nth occurance of a day of the week, and that you can't fiddle with whatever datetime datatype, and that you have access to both a get day of week and get day of month functions. Would Sunday be a zero?
1) First, the day of the week would have to match the day of the week given.
2) N would have to be at least 1 and at most 4.
3) The day of the month would range between n*7*dayOfWeek + 1 and n*7*dayOfWeek + 6 for the same n.
- Let me think about that. If Sunday was the first.. 0*7*0+1 = 1 and Saturday the 6th would be 0*7*0+6.
Think 1 and 3 above are sufficient since a get day of month function shouldn't violate 2.
(* first try, this code sucks *)
function isNthGivenDayInMonth(date : dateTime;
dow : dayOfWeek;
N : integer) : boolean;
var B, A : integer (* on or before and after day of month *)
var Day : integer (* day of month *)
begin
B := (N-1)*7 + 1; A := (N-1)*7 + 6;
D := getDayOfMonth(date);
if (dow <> getDayOfWeek(date)
then return(false)
else return( (B <= Day) and (A >= Day) );
end; (* function *)
Hope there isn't a bug in that lol!
[edit: Saturday would have been the 7th, and the upper bound above (N-1)*7 + 7.]
Your solution looks like it would match 2 different weeks? Looks like it would always return zero for Sundays? Should have done pseudocode in C#.. short circuit && is like my if..
hey shouldn't Sunday the first match for N = 1 in months that start on Sunday?
d/ 7 == n
That would result in (either 0 or 1)/7 == 1, that can't be right! Your || catches the (n-1) also, Robert has that. Go with Robert Wagner's answer! It's only 2 lines, short is good! Having (Day-1) mod 7
[edit: (Day-1) div 7]
eliminates my unnecessary variables and 2 lines of setup.
For the record this should be checked for boundary cases and so forth like what if August 31st was a Sunday or Saturday.
[edit: Should have checked the end of week case too. Sorry!]
You can find a function which returns a date for the nth occurrence of particular week day in any month.
See http://chiragrdarji.wordpress.com/2010/08/23/find-second-saturday-and-fourth-saturday-of-month/
In this answer, the following code needs to be flipped:
// Complete the gap to the nth week
dt = dt.AddDays((nth - 1) * 7);
if(dt.Month != month)
{
// we skip to the next month, we throw an exception
throw new ArgumentOutOfRangeException(”The given month has less than ” nth.ToString() ” ”
day_of_the_week.ToString() “s”);
}
Most of the answers above are partially accurate or unnecessarily complex.
You could try this simpler function, which also checks if the given date is the last but Nth day of the month.
public static bool IsNthDayofMonth(this DateTime date, DayOfWeek weekday, int N)
{
if (N > 0)
{
var first = new DateTime(date.Year, date.Month, 1);
return (date.Day - first.Day)/ 7 == N - 1 && date.DayOfWeek == weekday;
}
else
{
var last = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);
return (last.Day - date.Day) / 7 == (Math.Abs(N) - 1) && date.DayOfWeek == weekday;
}
In case you want a list of dates for a span of time (not just one) for the Nth DayOfWeek of a Month, you can use this:
internal static List<DateTime> GetDatesForNthDOWOfMonth(int weekNum, DayOfWeek DOW, DateTime beginDate, DateTime endDate)
{
List<DateTime> datesForNthDOWOfMonth = new List<DateTime>();
int earliestDayOfMonth = 1;
int latestDayOfMonth = 7;
DateTime currentDate = beginDate;
switch (weekNum)
{
case 1:
earliestDayOfMonth = 1;
latestDayOfMonth = 7;
break;
case 2:
earliestDayOfMonth = 8;
latestDayOfMonth = 14;
break;
case 3:
earliestDayOfMonth = 15;
latestDayOfMonth = 21;
break;
case 4:
earliestDayOfMonth = 22;
latestDayOfMonth = 28;
break;
}
while (currentDate < endDate)
{
DateTime dateToInc = currentDate;
DateTime endOfMonth = new DateTime(dateToInc.Year, dateToInc.Month, DateTime.DaysInMonth(dateToInc.Year, dateToInc.Month));
bool dateFound = false;
while (!dateFound)
{
dateFound = dateToInc.DayOfWeek.Equals(DOW);
if (dateFound)
{
if ((dateToInc.Day >= earliestDayOfMonth) &&
(dateToInc.Day <= latestDayOfMonth))
{
datesForNthDOWOfMonth.Add(dateToInc);
}
}
if (dateToInc.Date.Equals(endOfMonth.Date)) continue;
dateToInc = dateToInc.AddDays(1);
}
currentDate = new DateTime(currentDate.Year, currentDate.Month, 1);
currentDate = currentDate.AddMonths(1);
}
return datesForNthDOWOfMonth;
}
...and call it this way:
// This is to get the 1st Monday in each month from today through one year from today
DateTime beg = DateTime.Now;
DateTime end = DateTime.Now.AddYears(1);
List<DateTime> dates = GetDatesForNthDOWOfMonth(1, DayOfWeek.Monday, beg, end);
// To see the list of dateTimes, for verification
foreach (DateTime d in dates)
{
MessageBox.Show(string.Format("Found {0}", d.ToString()));
}
You could get the 2nd Friday of each month like so:
List<DateTime> dates = GetDatesForNthDOWOfMonth(2, DayOfWeek.Friday, beg, end);
...etc.
Here is a simple DateTime extension method to get the nth occurrence in a month.
/// <summary>
/// Gets the Nth occurrence of the specified weekday in the month.
/// </summary>
public static DateTime GetNthOfWeekDayInMonth(this DateTime dt, DayOfWeek dayOfWeek, int n)
{
//Get the first day of the month
DateTime fd = dt.AddDays(-dt.Day).AddDays(1);
// Get the FIRST occurrence of the specified weekday in the month.
fd = dayOfWeek >= fd.DayOfWeek ? fd.AddDays(dayOfWeek - fd.DayOfWeek) : fd.AddDays((7 + ((int)dayOfWeek)) - ((int)fd.DayOfWeek));
// Get the nth occurrence by adding the weeks
fd = fd.AddDays((n-1) * 7);
//Throw exception if you do not want to go past the specified month?
if (fd.Month != dt.Month) throw new Exception($"There is no {n} week in this month");
return fd;
}
Sample:
new DateTime(2022, 05, 12).GetNthOfWeekDayInMonth(DayOfWeek.Tuesday, 2);
// Output: [2022/05/10 00:00:00]