首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >DateTime.ParseExact将引发以下错误:“未将字符串识别为有效的DateTime”

DateTime.ParseExact将引发以下错误:“未将字符串识别为有效的DateTime”
EN

Stack Overflow用户
提问于 2018-06-06 08:57:58
回答 1查看 840关注 0票数 0

我正在为我的sharepoint构建一个控制台应用程序。现在我有一个名为"OrderLiveDeliveredDate“的DateTime字段,我想根据另一个名为"CustomerOrderContractLengthmonth”的字段值为它添加月份。

现在,"OrderLiveDeliveredDate“日期格式将类似于{15/06/2018 00:00:00}。因此,我编写了以下代码行来将字段值转换为DateTime,然后添加月份:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2018-06-06 09:04:40

你试过这个吗?

代码语言:javascript
复制
DateTime expiryDate = DateTime.ParseExact("15/06/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));

我已经从date string.If中去掉了time组件,你必须使用time组件,尝试如下...

代码语言:javascript
复制
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

代码:

代码语言:javascript
复制
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
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50710869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档