recently, I encountered the following problem: I obtained the time value string from a control and converted the string into a datetime object. The time value displayed in the control is: 12:23:34, but after I get this value through a function, we get 12:23:34, so when the set time format is: yyyy-mm-dd hh: mm: when the SS calls the datetime: parseexact function, an exception occurs, indicating that the time format does not match. This reminds us that after setting the time format, call datetime: parseexact to convert a string to a datetime object, make sure that the format of this string is consistent with the time format we set for conversion, otherwise there will be exceptions.
// The following Program is abnormal. The exception prompt is: the string is not recognized as a valid datetime.
using system. globalization;
namespace _ 3
{< br> class class1
{< br> static void main (string [] ARGs)
{< br> string mytime = " 12:23:34 ";
iformatprovider culture = new cultureinfo ("ZH-CN", true );
// The expected time format is month. The date must be two or fewer than two, enter 0 on the left.
string [] expectedformats = {" yyyy-mm-dd hh: mm: SS "};
datetime dt =
datetime. parseexact (mytime,
expectedformats,
Culture,
datetimestyles. allowinnerwhite);
console. writeline ("DT = {0}", DT);
}< BR >}
there are two Correction Methods:
1. string mytime = "12:23:34"; changed to: String mytime = "12:23:34";
2. expected format: String [] expectedformats = {"yyyy-mm-dd hh: mm: SS"}; changed to: String [] expectedformats = {"yyyy-m-D hh: MM: SS "};
// The following Code can match in milliseconds.
using system;
using system. globalization;
namespace _ 3
{< br> class class1
{< br> static void main (string [] ARGs)
{< br> string mytime = "12:23:34. 123 ";
iformatprovider culture = new cultureinfo (" ZH-CN ", true);
string [] expectedformats = {" yyyy-m-D hh: mm: SS. fff "};
datetime dt =
datetime. parseexact (mytime,
expectedformats,
Culture,
datetimestyles. allowinnerwhite);
console. writeline ("DT = {0}, millisecond: {1}", DT, DT. millisecond);
}< BR >}< br> the output result is: dt = 12:23:34, millisecond: 123