如何将日期字符串从“dd-MMM-yy”转换为“M / dd / yyyy hh:mm:ss tt”?

时间:2015-03-23 12:56:42

标签: c# date datetime cultureinfo date-parsing

我需要比较两个日期格式字符串:

" dd-MMM-yy"

dateString 格式

referenceDateString in" M / dd / yyyy hh:mm:ss tt"格式分别。

为此,我需要转换 dateString =" dd-MMM-yy"到" M / dd / yyyy hh:mm:ss tt"。

但是,尝试这样做时出错:

  

"错误:字符串未被识别为有效日期时间"。

我在下面给出的C#代码。

string dateString = "19-Dec-14";
string AsofDate = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

修改1:

在实际代码中, dateString 在读取以" 19-Dec-14"提供的csv文件后获取,这就是为什么它的原因以字符串格式。

请帮忙,我对C#很新。感谢。

2 个答案:

答案 0 :(得分:2)

Habib已经就他的评论给出了答案,我尝试将其添加为答案;

来自DateTime.ParseExact(String, String, IFormatProvider)

  

将指定的日期和时间字符串表示形式转换为它   DateTime等效使用指定的格式和特定​​于文化   格式信息。 字符串表示的格式必须匹配   指定的格式

在你的情况下,显然他们没有。首先,您需要使用正确的格式(string使用基于英语的文化)解析您的DateTimedd-MMM-yy,然后您就可以获得字符串了使用特定的格式代表您的DateTime

string s = "19-Dec-14";
DateTime dt;
if(DateTime.TryParseExact(s, "dd-MMM-yy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).Dump();
    // Result will be 12/19/2014 12:00:00 AM
}

答案 1 :(得分:0)

目前还不完全清楚你要做的是什么,但是为了解析你在第一行上的那个日期,你会使用这样的东西:

DateTime AsofDate = DateTime.ParseExact(dateString, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);

请注意以下几点:我已将AsofDate的数据类型从string更改为DateTime,因为DateTime.ParseExact返回的是"19-Dec-14"。另外,我修改了自定义格式字符串,以匹配您尝试解析为日期的字符串格式({{1}})。