using System.Globalization;
public static void Main()
var dateNow =new DateTime(2021,10,05,08,15,00);
var daysInMonth = DateTime.DaysInMonth(ToYear, ToMonth);
Console.WriteLine (@"daysInMonth"+daysInMonth);
var fromDate = new DateTime(FromYear,FromMonth, 1);
var toDate = new DateTime(ToYear, ToMonth, daysInMonth);
if (dateNow.Date == fromDate.Date)
fromDate = fromDate.AddMonths(-1);
toDate = toDate.AddDays(-1).AddMonths(-1);
Console.WriteLine (@"dateNow.Date == fromDate.Date");
Console.WriteLine (@"dateNow:"+dateNow.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"fromDate:"+fromDate.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"toDate:"+toDate.ToString("dd/MM/yyyy HH:mm:ss"));
TimeSpan avaiableCutOfTime;
if (!TimeSpan.TryParse("09:00", out avaiableCutOfTime))
Console.WriteLine (@"TimeSpan.TryParse avaiableCutOfTime");
Console.WriteLine ("Throw Error");
if (dateNow.TimeOfDay < avaiableCutOfTime)
toDate = toDate.AddDays(-1);
Console.WriteLine (@"dateNow.TimeOfDay < avaiableCutOfTime.TimeOfDay");
Console.WriteLine (@"dateNow:"+dateNow.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"fromDate:"+fromDate.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"toDate:"+toDate.ToString("dd/MM/yyyy HH:mm:ss"));
else if (dateNow.Month == ToMonth && dateNow.Year == ToYear)
toDate = dateNow.AddDays(-1);
Console.WriteLine (@"dateNow.Month == ToMonth && dateNow.Year == ToYear");
Console.WriteLine (@"dateNow:"+dateNow.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"fromDate:"+fromDate.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"toDate:"+toDate.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"fromDate > toDate");
Console.WriteLine ("Throw Error");
Console.WriteLine (@"dateNow:"+dateNow.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"fromDate:"+fromDate.ToString("dd/MM/yyyy HH:mm:ss"));
Console.WriteLine (@"toDate:"+toDate.ToString("dd/MM/yyyy HH:mm:ss"));