试图解析Exact以在C#中转换datetime的格式 [英] trying to parse Exact for converting the format of datetime in C#

查看:52
本文介绍了试图解析Exact以在C#中转换datetime的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用c#解析日期,并具有以下代码行


I am trying to parse a date in c# and have the following line of code


string dt =Convert.ToString( DateTime.FromFileTime(e8.sts[counter8].TimeStamp));
string format = "dd-MM-yyyy HH:mm:ss";
DateTime dateTime = DateTime.ParseExact(dt,format,CultureInfo.InvariantCulture);



当我调试dt时显示为"05/18/2011 09:25:17 AM",但我却期望说字符串未被识别为有效的DateTime."



when I debug dt is coming in as "05/18/2011 09:25:17 AM" but I get an expection saying "String was not recognized as a valid DateTime."

thanks in advance.

推荐答案

如果使用ParseExact,则需要以与变量format完全相同的格式传递数据.
您的格式显示为"dd-MM",但您的日期包含"/",因此解析失败.

尝试使用DateTime.Parse 甚至DateTime.TryParse代替.
If you use ParseExact, you will need to pass in the data in the exact same format as the variable format.
Your format says "dd-MM" but your date contains a "/" - hence parse fails.

Try using DateTime.Parse or even DateTime.TryParse instead.


不要使用Convert.ToString(通常避免无故使用Convert),使用DateTime.ToString相同您与Parse一起使用的确切文化.

—SA
Don''t use Convert.ToString (and generally, avoid using Convert without any reason), use DateTime.ToString with the same exact culture you use with Parse.

—SA


通过搜索google或任何搜索引擎网站.
By searching google or any search engine site.


这篇关于试图解析Exact以在C#中转换datetime的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆