C# datetime format change

前端 未结 3 461
天涯浪人
天涯浪人 2021-01-27 05:25

I want to convert datetime.now format which is \"dd/mm/yyyy hh:mm:ss AM/PM\" to US time format i.e. \"mm-dd-yyyy hh:mm:ss AM/PM\". More over i

3条回答
  •  清酒与你
    2021-01-27 06:08

    A DateTime value doesn't have a format. DateTime.Now doesn't have a format, and if you do any kind of conversion, if you've got a DateTime, there's no format. The concept of a format only applies when you're converting to or from a string - and DateTime.Now is a DateTime, not a string.

    Just insert the value into the database using DateTime.Now (or DateTime.UtcNow) and you'll preserve the data which is the important part.

    You should only perform string conversions when you actually have to - at which point you can use DateTime.TryParseExact and DateTime.ToString using custom date/time format strings. (Use TryParseExact for user input; for machine input which really should be valid, use DateTime.ParseExact.)

    Note that it's usually a good idea to use custom date/time patterns with the invariant culture, or standard date/time patterns with "real" cultures (e.g. the user's culture).

提交回复
热议问题