【问题标题】:How to add one year to a date and select a particular month如何将一年添加到日期并选择特定月份
【发布时间】:2017-04-18 16:31:00
【问题描述】:

如果NextInspectionDueDate 小于或等于今天的日期,那么我想将它的值更新为同一天但明年,特别是四月。

我尝试了以下方法,但它给出了“有一些无效参数”错误。 我只是想不出正确的语法。也许我应该换一种方式?

if (foundVehicle.Vehicle.NextInspectionDueDate <= DateTime.Now)
{
    foundVehicle.Vehicle.NextInspectionDueDate = new DateTime(DateTime.Now.AddYears(1), 4);
}

【问题讨论】:

  • 如果今天是31 Jan怎么办?结果应该是30 Apr 还是1 May
  • 您必须输入Day: ... new DateTime(DateTime.Now.AddYears(1), 4, 1); 才能拥有1 Apr 2018
  • DateTime.Now.AddYears 返回System.DateTime。你需要一个int
  • 附注:也许Noda Time 你也很感兴趣。
  • @Johnny Mopp,正确,提供的示例代码甚至无法编译

标签: c# datetime


【解决方案1】:

你刚刚忘记了构造函数的一个参数(月份中的哪一天):

foundVehicle.Vehicle.NextInspectionDueDate = new DateTime(DateTime.Now.AddYears(1).Year, 4, 1);

【讨论】:

  • 您的原始答案正是我想要的。不需要您的编辑答案,因为我特别想要 4 月 1 日。我已经编辑了这个问题以包括这个。谢谢!
  • @RMadd 感谢您的评论!我将删除编辑比! ;)
【解决方案2】:

你缺少一个参数(天),也许你可以试试:

var tempdate = DateTime.Now.AddYears(1); foundVehicle.Vehicle.NextInspectionDueDate = new DateTime(tempdate.Year, 4, tempdate.Day);

如果您需要保留当前日期日期

或者

var day = foundVehicle.Vehicle.NextInspectionDueDate.Day; var tempdate = DateTime.Now.AddYears(1); foundVehicle.Vehicle.NextInspectionDueDate = new DateTime(tempdate.Year, 4, day);

如果您需要保留原始日期日期

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2023-04-08
    相关资源
    最近更新 更多