EndDate Issue - Last Month of Year

81 Views Asked by At

I have a .netapp application (C#) that I use to extract data from an API.

It is having a problem just now as we are running this for December 2017.. but we want it to name as January 2018. (well 01/01/2018)

I think they way we have written it means it's looking for 13/2017 which obviously doesn't exist.

Can anyone recommend how to ammend this so we can run it just now and how we can ensure we don't run into this issue again next December?

public override string ToString()
    {
        var reportDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1);

        if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
        {
            var year = Int32.Parse(AppConfigHelper.EndDate.Substring(6, 4));
            var month = Int32.Parse(AppConfigHelper.EndDate.Substring(3, 2));
            var day = Int32.Parse(AppConfigHelper.EndDate.Substring(0, 2));
            reportDate = new DateTime(year, month, day);
            reportDate = reportDate.AddDays(1);
        }
1

There are 1 best solutions below

6
On BEST ANSWER

You can use DateTime.Today.AddMonths(1):

var nextMonth = DateTime.Today.AddMonths(1);
reportDate = new DateTme(nextMonth.Year, nextMonth.Month, 1);
// ...

By the way, you don't need string methods and int.Parse to get the DateTime, use ParseExact:

if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
{
    reportDate = DateTime.ParseExact(AppConfigHelper.EndDate, "ddMMyyyy", null);
    reportDate = reportDate.AddDays(1);
}