模糊日期到绝对日期的代码?

时间:2010-08-11 09:53:03

标签: c# .net datetime date

我需要带有字符串并确定日期的代码。我写了一个简单的15line函数来返回日期,假设它是相对的。那很简单。现在我需要输入一个字符串,如“jan 17 09”“1/2/3”(是MM / DD / YY?还是DD / MM / YY,这里的意思是前者)。我需要含糊不清的返回代码或异常。我可以用什么来解析这些绝对日期?

2 个答案:

答案 0 :(得分:0)

日期格式在很大程度上取决于您线程的当前文化设置。

答案 1 :(得分:0)

如果您了解需要处理的特定文化(您在对Leppie的答案的评论中提到),您只需使用System.Convert.ToDateTime函数将不明确的字符串转换为特定的绝对日期(使用指定的文化)。

例如:

string s1 = "jan 17 09";
string s2 = "1/2/3";
// Creates a specific culture, irrespective of the "local" culture,
// in this case, Japanese.
CultureInfo culture = CultureInfo.CreateSpecificCulture("ja-JP");
DateTime d1 = Convert.ToDateTime(s1, culture);
DateTime d2 = Convert.ToDateTime(s2, culture);
Console.WriteLine(d1.ToLongDateString());
Console.WriteLine(d2.ToLongDateString());