簡體   English   中英

C#字符串迄今與CultureInfo

[英]C# String to date with CultureInfo

我有以下格式的日期。 始終采用這種格式。

yyyyMMdd  ->  20130912

我需要將其轉換為日期。 但是我需要確保將日期轉換為PC的正確日期格式。 Cultureinfo.InvariantCulture。 這是我的代碼現在的樣子。

DateTime parsedDateTime;
int year = Int32.Parse(rows[row][4].ToString().Substring(0, 4));
int month = Int32.Parse(rows[row][4].ToString().Substring(4, 2));
int day = Int32.Parse(rows[row][4].ToString().Substring(6, 2));
DateTime value = new System.DateTime(year, month, day);

bool DateTimeParseFail = DateTime.TryParse(value.ToString("yyyy-MM-dd"),   CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime);

if (!DateTimeParseFail) {
   msg = "Data Feed Convert string to DateTime: Date " + rows[row][4].ToString() + " - " + value.ToString();
   ComponentMetaData.FireError(0, ComponentMetaData.Name, msg, string.Empty, 0, out pbCancel);
   throw new Exception(msg);
}  else {
   buffer[colIndex] = parsedDateTime;
}

對我來說,這似乎有點過分,我懷疑我對此考慮過度。 必須有一種更簡單的方法來執行此操作。 但是我嘗試過的所有方法都沒有達到我的預期。

嘗試這個:

string dateText = rows[row][4].ToString();
DateTime date = DateTime.ParseExact(dateText, "yyyyMMdd", CultureInfo.InvariantCulture);
string result = date.ToShortDateString(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern);

請注意,我假設您斷言日期始終采用這種格式是正確的。 如果不是,您會發現代碼拋出異常。

(您發布的代碼表明您的斷言不正確,因為那里有一個后備格式和一些失敗處理方法。)

使用DateTime的TryParseExact。

var dateString = "20130912"; //rows[row][4].ToString()
DateTime parsedDateTime;
var DateTimeParseFail= DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime);

if (!DateTimeParseFail) {
   msg = "Data Feed Convert string to DateTime: Date " + rows[row][4].ToString() + " - " + value.ToString();
   ComponentMetaData.FireError(0, ComponentMetaData.Name, msg, string.Empty, 0, out pbCancel);
   throw new Exception(msg);
}  else {
   buffer[colIndex] = parsedDateTime;
}

暫無
暫無

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

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