Convert YYYYMMDD string to MM/DD/YYYY string

前端 未结 4 1923
庸人自扰
庸人自扰 2021-01-06 09:27

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a \'MM/DD/YYYY\' format. I am programming in c#. The current code tha

相关标签:
4条回答
  • 2021-01-06 10:06

    Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).

    DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);
    

    Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:

    DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
    

    Then your code will work.

    0 讨论(0)
  • 2021-01-06 10:11

    You want the method DateTime.ParseExact.

    DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2021-01-06 10:21

    DateTime.ParseExact with an example

    string res = "20120708";
    DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
    Console.WriteLine(d.ToString("MM/dd/yyyy"));
    
    0 讨论(0)
  • 2021-01-06 10:24

    Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.

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