0

我有一个用于从 API 提取数据的 .netapp 应用程序 (C#)。

它刚刚出现问题,因为我们在 2017 年 12 月运行它。但我们希望它命名为 2018 年 1 月。(好吧 01/01/2018)

我认为我们编写它的方式意味着它正在寻找显然不存在的 13/2017。

谁能推荐如何修改它以便我们现在可以运行它以及我们如何确保我们不会在明年 12 月再次遇到这个问题?

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);
        }
4

1 回答 1

3

您可以使用DateTime.Today.AddMonths(1)

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

顺便说一句,您不需要字符串方法并int.Parse获得DateTime,使用ParseExact

if (!String.IsNullOrWhiteSpace(AppConfigHelper.EndDate))
{
    reportDate = DateTime.ParseExact(AppConfigHelper.EndDate, "ddMMyyyy", null);
    reportDate = reportDate.AddDays(1);
}
于 2017-12-04T10:56:29.733 回答