【问题标题】:Adding a number to the day or month or year in a date [duplicate]在日期中的日、月或年中添加数字[重复]
【发布时间】:2013-01-05 11:09:23
【问题描述】:

可能重复:
How to add days to a date in Java

假设日期为 19/05/2013,数字为 14。我想在将数字添加到月份后得到结果日期。

预期结果是:2014 年 7 月 19 日。

【问题讨论】:

  • @CodeEnthusiastic 您可能应该在问题中提到这一点。另外,使用内置方法有什么问题?
  • “我试图避免使用内置方法” 这是问题中应该包含的信息,您应该尝试什么来实现这一点。
  • @CodeEnthusiastic,为什么要避免使用内置方法?
  • 您不应该试图避免使用内置方法。这就是为什么它们是内置的。为了避免你重新发明轮子。只有当你想在脚上开枪时,你才应该这样做。是你想要的吗?避免它们并没有改善任何东西。您正在射击自己或使用并不得不维护您的代码的人。
  • @CodeEnthusiastic,提供了这些内置的抽象方法,这样您就不必重新发明轮子并在业务逻辑上投入更多精力。 提高逻辑能力和验证我认为这不是提高逻辑能力的最佳方法

标签: c# java algorithm date


【解决方案1】:

在 .NET 中,您可以使用 AddMonths 方法:

DateTime date = new DateTime(2013, 5, 19);
DateTime newDate = date.AddMonths(14);

就使用指定格式从字符串中解析日期而言,您可以使用TryParseExact 方法:

string dateStr = "19/05/2013";
DateTime date;
if (DateTime.TryParseExact(dateStr, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    // successfully parsed the string into a DateTime instance =>
    // here we could add the desired number of months to it and construct
    // a new DateTime
    DateTime newDate = date.AddMonths(14);
}
else
{
    // parsing failed => the specified string was not in the correct format
    // you could inform the user about that here
}

【讨论】:

  • 是的,正确的。答案已更新。
【解决方案2】:

您可以DateTime.AddMonths添加月份。

DateTime date = new DateTime(2013, 5, 19);
DateTime newDate = date.AddMonths(14);

【讨论】:

    【解决方案3】:

    在 Java 中:

    Calendar c = Calendar.getInstance();
    c.setTime(new Date()); // today is the default
    c.add(Calendar.DATE, 1);  // number of days to add (1)
    c.getTime();  // The new date
    

    【讨论】:

      【解决方案4】:

      只需使用 AddMonths 将指定的月数添加到此实例的值中。

      DateTime date = new DateTime(2013, 5, 19);   // (yyyy,MM,dd)
      DateTime dt = date.AddMonths(14);
      

      【讨论】:

        猜你喜欢
        • 2014-09-17
        • 1970-01-01
        • 2014-09-08
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        • 1970-01-01
        • 2017-07-13
        • 1970-01-01
        相关资源
        最近更新 更多