簡體   English   中英

將字符串日期和時間轉換為DateTime

[英]Convert a string Date and Time to a DateTime

我必須遍歷數千個Word文檔並從中創建XML文件。 除日期字段外,其他所有東西都可以正常工作,因為我使用的是兩種語言。

這里有一些例子

  • 日期:2016年11月24日時間:15:31
  • 日期:2016年11月28日時長:10H31

我使用下面的代碼清理了一下字符串,但是仍然得到臭名昭著的“字符串未被識別為有效的DateTime”。

IFormatProvider culture = null;
if (m.rdoEnglish.IsChecked == true)
{
    culture = new System.Globalization.CultureInfo("en-CA", true);
}
else if (m.rdoFrench.IsChecked == true)
{
    culture = new System.Globalization.CultureInfo("fr-CA", true);
}

string dt = "";
dt = m.txtPublished.Text;

if (dt.IndexOf("HEURE:") != -1)
{
    dt = dt.Replace("HEURE:", "");
}

if (dt.IndexOf("H") != -1)
{
    dt = dt.Replace("H", ":");
}
DateTime dt2;
dt2 = DateTime.ParseExact(dt, "MM/dd/yyyy HH:mm:ss tt", culture);

//Cleaned string looks like this " 28 NOVEMBRE 2016 10:31  "
return dt2;

根據您給出的兩個示例,看來您的格式字符串不正確。 它應該類似於“ MMMM dd,yyyy hh:mm”。有關更多信息,請訪問: DateTime.ParseExact方法

ParseExact和TryParseExact具有重載,該重載接受用於解析字符串的格式數組。 這將允許您使用類似這樣的東西

string test = dt.Replace("DATE: ", "")
                .Replace("TIME: ", "")
                .Replace("HEURE: ", "");

string[] formats = new string[]
{
    "MMMM dd, yyyy HH:mm", "dd MMMM yyyy HH\'H\'mm"
};
DateTime dt2 = DateTime.ParseExact(test, formats, culture, DateTimeStyles.None);

請注意,我不嘗試在法語字符串的字符串中替換單個char H,因為我不知道在您的月份中是否出現相同的char。

如果您需要解析的字符串可以在同一文檔中處於兩種不同的區域性,則您需要進行更具防御性的編碼。

建立兩種文化:

IFormatProvider englishCulture = new System.Globalization.CultureInfo("en-CA", true);
IFormatProvider frenchCulture = new System.Globalization.CultureInfo("fr-CA", true);

然后將TryParse與一種區域性結合使用,如果失敗,則嘗試另一種區域性:

DateTime output;
if (DateTime.TryParseExact(input, frenchFormatString, frenchCulture, out output))
{
    // Read it successfully
}
else if (DateTime.TryParseExact(input, englishFormatString, englishCulture, out output))
{
    // Read it successfully 
}
else
{
    // Unknown format, try something else?
}

如果您知道該文本應為法語或英語,則可以安排代碼,以便首先嘗試最有可能的區域性。

格式字符串可以包含所有填充字以及實際數據的占位符。 甚至有一個TryParseExact重載,它需要一組格式字符串,因此您可以設置將遇到的所有(或至少大多數)格式。

暫無
暫無

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

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