简体   繁体   English

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

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

I want to accept date in dd-MM-yyyy format using textbox I have used ajax calendar also. 我想使用文本框接受dd-MM-yyyy格式的日期,我也使用了ajax日历。

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

and

Convert.ToDateTime(txtDate.Text) 

are both throwing exception: 都抛出异常:

string was not recognized as valid datetime. 字符串未被识别为有效的日期时间。

I know when I will change my system dateformat which is currently MM-dd-yyyy to dd-MM-yyyy , it will start recognizing it but what is solution when I will publish it on server. 我知道何时将当前为MM-dd-yyyy系统dateformat更改为dd-MM-yyyy ,它将开始识别它,但是当我将其发布到服务器上时,解决方案是什么。

So is there any solution to parse it for current format ? 那么,有什么解决方案可以将其解析为当前格式吗?

You need to pass an IFormatProvider parameter to the ParseExact method like : 您需要将IFormatProvider参数传递给ParseExact方法,例如:

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

And don't forget to use the System.Globalization namespace 并且不要忘记使用System.Globalization命名空间

You need to use System.Threading.Thread.CurrentThread.CurrentCulture to get the user's current settings. 您需要使用System.Threading.Thread.CurrentThread.CurrentCulture来获取用户的当前设置。 Then use that to get the formatted date string. 然后使用它来获取格式化的日期字符串。

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

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

相关问题 获取错误“字符串未被识别为有效的DateTime”。 - Getting error “String was not recognized as a valid DateTime.” 如何在没有得到“字符串未被识别为有效的日期时间”的情况下转换日期。 - 错误? - How to convert dates without getting 'String was not recognized as a valid DateTime.'-error? 该字符串未被识别为有效的DateTime。 日期格式为文本 - The string was not recognized as a valid DateTime. Date in text format “字符串未被识别为有效的日期时间。” 格式“yyyy-MM-dd”我如何使用这种格式 - "String was not recognized as a valid DateTime." format "yyyy-MM-dd" how i can use this format 字符串日期未被识别为有效的日期时间。 - String date was not recognized as a valid DateTime.' 错误消息为“字符串未被识别为有效的DateTime。” - Error Message as “String was not recognized as a valid DateTime.” 无法将字符串识别为有效的DateTime。 引发异常 - String was not recognized as a valid DateTime. Throws an Exception 错误:字符串未被识别为有效的DateTime。 - Error: String was not recognized as a valid DateTime. 字符串未被识别为有效的日期时间。 将字符串转换为日期时间 - String was not recognized as a valid DateTime. Converting string to DateTime DateTime.ParseExact赋予String未被识别为有效的DateTime。 - DateTime.ParseExact gives String was not recognized as a valid DateTime.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM