簡體   English   中英

DateTime.ParseExact FormatException字符串未被識別為有效的DateTime

[英]DateTime.ParseExact FormatException String was not recognized as a valid DateTime

我完全被這個困擾了。 據我所知,文件和其他帖子我已經讀過,說這應該有效。 我一定是想念一些傻事,但我看不出來。

我得到一個FormatException,消息“字符串未被識別為有效的DateTime”。 在以下代碼行:

return DateTime.ParseExact(value, DateFormat, null,
                           DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);
  • value"11/04/2013"
  • DateFormat"dd/MM/yyyy"
  • 目前的文化是en-GB
  • 我嘗試了各種DateTimeStyles變種但沒有效果。

我最初的意圖是格式為ddd, dd/MMM/yyyy但是也沒有用(該實例中的值是Tue, 30/Apr/2013

我也嘗試通過傳入new CultureInfo("en-GB")而不是null來強制文化到en-GB

我還將代碼解壓縮到自己的控制台應用程序中,以查看環境是否存在差異(ASP.NET MVC 3)

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var DateFormat = "dd/MM/yyyy";
            var value = "30/04/2013";
            var culture = new CultureInfo("en-GB");
            var result = DateTime.ParseExact(value, DateFormat, culture,
                           DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);
            Console.WriteLine("\"{0}\" as \"{1}\" ==> {2}", value, DateFormat, result);
            Console.ReadKey();
        }
    }
}

這仍然給我同樣的錯誤。

這有用嗎

 string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt", 
                                           CultureInfo.InvariantCulture)
string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy HH:mm:ss:tt",  
                                           CultureInfo.InvariantCulture);

注意使用HH(24小時制)而不是hh(12小時制),以及使用InvariantCulture,因為有些文化使用除斜線之外的分隔符。

例如,如果文化是de-DE,則格式“dd / MM / yyyy”會將期間視為分隔符(31.01.2011)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM