代码之家  ›  专栏  ›  技术社区  ›  john Gu

datetime.parseExact引发以下错误“字符串未被识别为有效的datetime”

  •  0
  • john Gu  · 技术社区  · 6 年前

    我正在为我的sharepoint构建一个控制台应用程序。现在我有一个名为“orderLiveDeliveredDate”的日期时间字段,我想根据另一个名为“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 .

    2 回复  |  直到 6 年前
        1
  •  2
  •   Jonathon Chase    6 年前

    DateTime.ParseExact 要求格式字符串完全匹配。

    从文件上看,

    使用指定的格式和区域性特定的格式信息,将日期和时间的指定字符串表示形式转换为其等效的日期时间。字符串表示的格式 必须与指定的格式完全匹配。

    (强调我的。)

    在你的情况下,你会想要 "{dd/MM/yyyy HH:mm:ss}" 作为格式字符串,假设 {15/06/2018 00:00:00} 实际值是否存储在 item["OrderLiveDeliveredDate"] . 如果大括号不是字符串的成员,则 "dd/MM/yyyy HH:mm:ss" 应该工作得很好。

        2
  •  2
  •   AD8    6 年前

    你试过这个吗?

    DateTime expiryDate = DateTime.ParseExact("15/06/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));
    

    我已从日期字符串中删除时间组件。如果必须使用时间组件,请尝试下列操作…

    DateTime expiryDate = DateTime.ParseExact("15/06/2018 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture).AddMonths(int.Parse("2"));
    

    快速测试仪- 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
            }
        }
    }