Use datetime. Now. tostring () with caution ()

Source: Internet
Author: User

For example, when the date in regional options is set:

Date Format: yyyy-mm-dd

Time settings:

Time Format: TT hh: mm: SS

Am Symbol: Morning

PM Symbol: PM

Console. writeline (datetime. Now. tostring ());

Output result: 02:11:56

Obviously, if you directly store this value in the database, a similar exception will be obtained: syntax error converting datetime from character string.

If you directly convert this string, such as datetime. prase ("02:11:56 "),CodeIf the date and time format of the current region is changed, the string was not recognized as a valid datetime.

Solution: Use the datetime. tostring (string format) method to convert the value of this instance to its equivalent string representation using the specified format.

Code
Datetime dt=Datetime. parse (datetime. Now. tostring ("Yyyy-mm-dd hh: mm: SS"));

In this case, the datetime output format is controlled by the format parameter and is irrelevant to the date/time setting in regional options.

 

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.