我正在为我的sharepoint构建一个控制台应用程序。现在我有一个名为"OrderLiveDeliveredDate“的DateTime字段,我想根据另一个名为"CustomerOrderContractLengthmonth”的字段值为它添加月份。
现在,"OrderLiveDeliveredDate“日期格式将类似于{15/06/2018 00:00:00}
。因此,我编写了以下代码行来将字段值转换为DateTime,然后添加月份:
DateTime expiryDate = DateTime.ParseExact(item["OrderLiveDeliveredDate"].ToString(), "dd/mm/yyyy", CultureInfo.InvariantCulture).AddMonths(int.Parse( item["CustomerOrderContractLengthmonth"].ToString()));
但这引发了以下异常:
String was not recognized as a valid DateTime
。
发布于 2018-06-06 09:04:40
你试过这个吗?
DateTime expiryDate = DateTime.ParseExact("15/06/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));
我已经从date string.If中去掉了time组件,你必须使用time组件,尝试如下...
DateTime expiryDate = DateTime.ParseExact("15/06/2018 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));
用于快速测试的Rextester - http://rextester.com/HYEU95556
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
DateTime expiryDate = DateTime.ParseExact("15/06/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));
DateTime expiryDate2 = DateTime.ParseExact("15/06/2018 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));
Console.WriteLine(expiryDate); //15.08.2018 00:00:00
Console.WriteLine(expiryDate2); //15.08.2018 00:00:00
}
}
}
https://stackoverflow.com/questions/50710869
复制相似问题