简体   繁体   中英

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.

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.

So is there any solution to parse it for current format ?

You need to pass an IFormatProvider parameter to the ParseExact method like :

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

And don't forget to use the System.Globalization namespace

You need to use System.Threading.Thread.CurrentThread.CurrentCulture to get the user's current settings. Then use that to get the formatted date string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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