I’m trying to render a view that show some records between two dates, when no parameter is passed the view must show the records of one month starting the 5th day until next 5th day of the next month.
right now i did it, but i’m concerned about my code, is there another way to do this i mean, get my code to look better.
var dateStart = new DateTime();
var dateEnd = new DateTime();
if(dateTime !=null)
{
dateStart = Convert.ToDateTime(dateTime);
dateEnd = new DateTime(dateStart.Year, dateStart.Month + 1, 5);
}
else
{
if (DateTime.Today.Day <= 4)
{
DateTime lastMonth = DateTime.Today.AddMonths(-1);
dateStart = new DateTime(lastMonth.Year, lastMonth.Month, 5);
dateEnd = new DateTime(dateStart.Year, dateStart.Month + 1, 5);
}
DateTime date = DateTime.Today;
dateStart = new DateTime(date.Year, date.Month, 5);
dateEnd = new DateTime(date.Year, date.Month + 1,5);
}
You shouldn’t add on months like that as you’ll end up with invalid
DateTimecome December when it tries to create a DateTime that has a month of 13, so I’d use theAddMonthsmethod instead. You also appear to need anotherelse statementadding so that the secondif statementisn’t irrelevant. I’ve simplified the code slightly, was this what you meant?