C# datetime format change

前端 未结 3 462
天涯浪人
天涯浪人 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:05
    DateTime usDateTimeFormat = DateTime.Parse(DateTime.Now , 
    System.Globalization.CultureInfo.GetCultureInfo("en-us"));
    
    0 讨论(0)
  • 2021-01-27 06:07

    Try this. Standard Date and Time Format Strings

    DateTime.Now.ToString("g",CultureInfo.CreateSpecificCulture("en-us"))
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题