简体   繁体   中英

DateTime.TryParse() not working with formatted date dd/MM/yyyy

This code returns (min time 1/1/0001 12:00:00 AM) not Date.Time.Now . Try Parse works for MM/dd/yyyy but not dd/MM/yyyy . Any suggestions

Here is code

DateTime start, end;
DateTime.TryParse(EPSDate12.Text, out start);
string  TNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); // Works
//   string  TNow = DateTime.Now.ToString();// works but gives MM/dd/yyyy as expected 
DateTime.TryParse(TNow, out end); // No. gives min time (1/1/0001 12:00:00 AM)

Use TryParseExact and supply the format string.

Also examine the return value from TryParseExact to know if it failed or not (it returns a bool)

I see "EPSDate12.Text" which i suspect may be a TextBox: If you're doing this in a UI, make life easy and use a DateTimePicker - you can set the format, the user can type into them just like a textbox, but they don't accept invalid inputs, and all you have to do is get the .Value property which gives you a DateTime


As to why your attempts to parse the string you made don't work, I think it most likely that the date format Parse is using (which is based on the culture settings of the executing thread) is not the same format as the string you prepared using your forced format. Either make sure your forced format is matched to the current culture, or use a culture that matches your forced format, or use [Try]ParseExact to force the format for parsing like you did when creating the string

See https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-5.0#Culture for more info

The datetime value is internally the same. But, ToString() return value, depends on the local machine culture setup.

Reference article

The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default DateTime.ToString() method.

For en-US culture( MM/dd/yyyy hh:mm:ss ) , it will be in

7/28/2021 11:37:40 AM

If you want to see in en-GB( dd/MM/yyyy hh:mm:ss ), you can apply conversion as given below:

var culture = new CultureInfo("en-GB");
MessageBox.Show($"{DateTime.Now.ToString(culture)}");

28/07/2021 11:45:09 AM

you can also specify exact custom format, in which you want to display.

MessageBox.Show($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss tt")}");

28/07/2021 11:45:09 AM

Thanks for suggestions . Yes DateTime.TryParse is not working and it could be format issue This line of code. string TNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

generates 29/07/2021 14:49:03 which looks OK but fails TryParse

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