2012-07-26 49 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);