Possible Errors in DateTime and String Conversion

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.