加入多种的一天或一个月或一年中的日期 [英] Adding a number to the day or month or year in a date

查看:129
本文介绍了加入多种的一天或一个月或一年中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  如何天添加到Java的 <日期/ P>

考虑日期为 19/05/2013 和数字是 14 。我想加入数月后得到结果日期。

预期的结果是:19/07/2014

解决方案

在.NET中,你可以做使用<一个href="http://msdn.microsoft.com/en-us/library/system.datetime.addmonths.aspx"><$c$c>AddMonths方法:

 日期时间日期=新的日期时间(2013,5,19);
日期时间newDate = date.AddMonths(14);
 

至于使用指定的格式,你可以使用分析从一个字符串的日期的<一个href="http://msdn.microsoft.com/en-us/library/system.datetime.TryParseExact.aspx"><$c$c>TryParseExact方法:

 字符串dateStr =19/05/2013​​;
日期时间日期;
如果(DateTime.TryParseExact(dateStr,DD / MM / YYYY,CultureInfo.InvariantCulture,DateTimeStyles.None,过时))
{
    //成功解析的字符串转换成一个DateTime实例=&GT;
    //这里我们可以添加个月的期望数量的它和构造
    //一个新的datetime
    日期时间newDate = date.AddMonths(14);
}
其他
{
    //分析失败=&GT;指定的字符串的不正确的格式
    //可以通知用户,在这里
}
 

Possible Duplicate:
How to add days to a date in Java

Consider the date to be 19/05/2013 and the number to be 14. I would like to get the resulting date after adding the number to the month.

Expected result is: 19/07/2014.

解决方案

In .NET you could do use the AddMonths method:

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

As far as parsing a date from a string using a specified format you could use the TryParseExact method:

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
}

这篇关于加入多种的一天或一个月或一年中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆