2012-07-26 88 views
4

我有一個字符串,其中包含日期和格式爲「MMMyy」。如何做到這一點?
樣品:C#日期時間解析短字符串(「MMMyy」)

string date = "MAY09"; 
DateTime a = DateTime.Parse("MAY09"); //Gives "2012.05.09 00:00:00" 
DateTime b = DateTime.ParseExact("MAY09", "MMMyy", null); //Gives error 
DateTime c = Convert.ToDateTime("MAY09"); //Gives "2012.05.09 00:00:00" 

I need "2009-05-01" 
+0

'null'將意味着當前的文化你嘗試與InvariantCulture的? – V4Vendetta 2012-07-26 06:41:24

+0

是的!謝謝。 InvariantCulture做了訣竅。 – JNM 2012-07-26 06:48:07

回答

7

指定3 第三參數,而不是null不變文化:

DateTime b = DateTime.ParseExact("MAY09", "MMMyy", CultureInfo.InvariantCulture); 
4

第二個是你想要的 - 不是用正確的文化等。 null表示使用當前文化中的日期/時間格式信息 - 如果它不是英語文化,將會失敗。 (這不是與您所在的用戶配置文件明確,但可能不是在英語文化?)

指定不變文化是獲得英語月/日的名稱的簡單方法:

using System; 
using System.Globalization; 

class Test 
{ 
    static void Main() 
    { 
     string text = "MAY09"; 
     string pattern = "MMMyy"; 
     var culture = CultureInfo.InvariantCulture; 
     DateTime value = DateTime.ParseExact(text, pattern, culture); 
     Console.WriteLine(value.ToString("yyyy-MM-dd", culture)); 
    } 
} 
0

你可以直接指定的日期/時間格式的ToString方法的參數

string dateTime = DateTime.Now.ToString("MMMyy"); 
0

這應有助於:

string date = "MAY09"; 
CultureInfo s = new CultureInfo("en-US"); 
DateTime b = DateTime.ParseExact(date, "MMMyy", s); 
0

請嘗試以下代碼:

string date = "MAY09"; 
CultureInfo culture = CultureInfo.GetCultureInfo("en-US"); 
DateTime dateTime = DateTime.ParseExact(date,"MMMyy",culture);