在日期的日期,月份或年份中添加数字
问题内容:
考虑日期为 2013年5 月19日 ,数字为 14 。将数字加到月份后,我想得到结果日期。
预期结果是:19/07/2014。
问题答案:
在.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
}