繁体   English   中英

始终获取字符串未被识别为有效的日期时间。 如何转换为当前格式

[英]always getting string was not recognized as valid datetime. how to convert for current format

我想使用文本框接受dd-MM-yyyy格式的日期,我也使用了ajax日历。

DateTime.ParseExact(txtDate.Text,"dd-MM-yyyy",null) 

Convert.ToDateTime(txtDate.Text) 

都抛出异常:

字符串未被识别为有效的日期时间。

我知道何时将当前为MM-dd-yyyy系统dateformat更改为dd-MM-yyyy ,它将开始识别它,但是当我将其发布到服务器上时,解决方案是什么。

那么,有什么解决方案可以将其解析为当前格式吗?

您需要将IFormatProvider参数传递给ParseExact方法,例如:

CultureInfo provider = CultureInfo.GetCultureInfo("en-US")
DateTime.ParseExact(txtDate.Text,"dd-MM-yyyy",provider) 

并且不要忘记使用System.Globalization命名空间

您需要使用System.Threading.Thread.CurrentThread.CurrentCulture来获取用户的当前设置。 然后使用它来获取格式化的日期字符串。

DateTime now = DateTime.Now;
string formattedToCurrentUser = now.ToString(System.Threading.Thread.CurrentThread.CurrentCulture);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM