将字符串转换为有效日期时间 [英] converting string to valid datetime

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

问题描述

string strdate="15/06/2010";

DateTime dt = 
     DateTime.Parse(strdate, 
     System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);

我不能抽到了日期时间值DD / MM / YYYY。 它给异常字符串未被识别为有效的日期时间

i cannot able to get the datetime value as dd/mm/yyyy. it is giving exception 'string is not recognized as a valid datetime'

OLY如果它是在2010年6月15日,它正在。如何获得相同的格式中dt的

oly if it is in 06/15/2010 it is working. how to get the same format in dt.

推荐答案

嗯,presumably你的线程的当前区域性预计MM / DD / YYYY。如果你想使用DD / MM / YYYY那么你应该明确指定。我个人preFER ParseExact 而不是解析,因为这提供了更多的控制权。我会用这样的:

Well, presumably your thread's current culture expects MM/dd/yyyy. If you want to use dd/MM/yyyy then you should specify that explicitly. Personally I prefer ParseExact instead of Parse, as that gives more control. I would use something like:

DateTime dt = DateTime.ParseExact(strdate, "dd/MM/yyyy",
    CultureInfo.InvariantCulture);

请注意,如果这是用户的输入,您可能需要使用 TryParseExact 代替。

Note that if this is user input, you may want to use TryParseExact instead.

这篇关于将字符串转换为有效日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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