使用c#将字符串转换为datetime的问题 [英] problem converting string to datetime using c#

查看:49
本文介绍了使用c#将字符串转换为datetime的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我将字符串转换为日期时间有问题。

Hi,
I have a problem converting string to datetime.

string datestr="14/2/2015";
DateTime x1;
                        string pattern = "dd-MM-yyyy";
                        DateTime.TryParseExact(EndDate, pattern, null, DateTimeStyles.None, out x1);
                        DateTime.TryParse(EndDate, out x1);
                        DateTime.TryParseExact(EndDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out x1);
output like this 1/1/0001 12:00:00 AM

if I am using x1 = Convert.ToDateTime(datestr); 
I got exception.





请帮帮我

谢谢



please help me
Thanks

推荐答案

帮助你做什么?你想要这个:
help you with what exactely ? do you want this :
x1 = Convert.ToDateTime(datestr); 

能正常工作吗?然后你必须阅读这个 https://msdn.microsoft.com/en -us / library / 9xk1h71t(v = vs.100).aspx [ ^ ]并注意如果provider为null,则使用当前文化的DateTimeFormatInfo。



鉴于您提供的内容,看起来14/2/2015对于您当前的文化设置不正确 - 我先试试这个



to work properly ? then you have to read this https://msdn.microsoft.com/en-us/library/9xk1h71t(v=vs.100).aspx[^] and pay attention to " If provider is null, the DateTimeFormatInfo for the current culture is used."

Given what you've supplied, it would appear as if "14/2/2015" isn't correct for your current culture setting - I'd try this first

string datestr="14/2/2015";
CultureInfo culture = new CultureInfo("en-GB");
DateTime x1 = Convert.ToDateTime(datestr,culture );





如果有效,你知道你的文化背景很可能en-US或其他内容(在这种情况下'en-US'字符串应格式化为2015年2月14日)



and if that works you know your culture setting is likely 'en-US' or something else (in which case of 'en-US' the string should be formatted "2/14/2015")


因为您的默认文化格式是US

Because your default culture format is en-US
string datestr="14/2/2015";



它的意思是:MM / dd / YYYY

程序检测:


It's mean: MM/dd/YYYY
Program detect:

Month = 14
Day = 2
Year = 2015



=>所以你应该改为:

1 /


=> so you should change as:
1/

string datestr="02/14/2015";
DateTime dt = Convert.ToDateTime(datestr);



希望这个帮助!


Hope this help!


这篇关于使用c#将字符串转换为datetime的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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