Convert string to DateTime
During development, there are often requirements for mutual conversion between the DataTime and String types.
Var date = Convert. ToDateTime ("09:10:10 ");
At first glance, there seems to be no problem with this code, and no problems have been found during actual operation. However, there is a conversion exception on the customer's machine.
After investigation, it was found that the system setting of the customer's computer was in Spain. In this case, the Code considers 09:10:10 as not a valid date string.
The correct statement should be:
Var dtFormat = new DateTimeFormatInfo {LongDatePattern = "yyyy/MM/dd hh: mm: ss"}; // specify to convert the format to DateTime
Var date = Convert. ToDateTime ("09:10:10", _ dtFormat)
Convert DateTime to string
Var dateString = System. DateTime. Now. ToString ()
In this way, the converted string will also have different output formats based on the running system's CultureInfo.
For clients such as WCF, Web service, and Ajax and servers with different CultureInfo, errors are very easy.
When converting to a string, add CultureInfo. InvariantCulture
Var dateString = System. DateTime. Now. ToString (CultureInfo. InvariantCulture)
At the same time, when the string is converted back,
Var date = DateTime. Parse (serverInfo. ServerDateTimeString, CultureInfo. InvariantCulture)
This CultureInfo is a bit like an English format, but it is not linked to a country or region, it can provide a reliable standard format in a multilingual environment
From JustRun1983