Date formatting yyyymmdd to yyyy-mm-dd

前端 未结 9 1886
长情又很酷
长情又很酷 2020-12-17 00:36

I\'m trying to convert a date in yyyymmdd format to yyyy-mm-dd with the following code:

tdrDate = DateTime.ParseExact(dateString, \"yyyymmdd\", null).ToStrin         


        
相关标签:
9条回答
  • 2020-12-17 01:10
    tdrDate = DateTime.ParseExact(dateString, "yyyyMMdd", null).ToString("yyyy-MM-dd");
    

    You need MM, not mm. mm is for minutes.

    0 讨论(0)
  • 2020-12-17 01:11

    Disclaimer I know nothing about C#'s date formatting.

    But I'm guessing the problem is that you used mm in the first format string, and MM in the second.

    0 讨论(0)
  • 2020-12-17 01:13

    Here you're parsing the date to create a date object, formatting the date object to a string, and discarding the date object. That sounds like more work than simple string processing:

    tdrDate = dateString.Substring(0,4) + '-' + 
        dateString.Substring(4,2) + '-' + 
        dateString.Substring(6,2);
    

    Unless you need the validation that's performed by DateTime.ParseExact(), which will throw a System.FormatException if given an invalid date, I'd probably just use the string formatting approach.

    0 讨论(0)
  • 2020-12-17 01:14

    "yyyymmdd" must be "yyyyMMdd".

    mm is for minutes.

    0 讨论(0)
  • 2020-12-17 01:16

    Try this :

    tdrDate = DateTime.ParseExact(dateString, "yyyyMMdd", null).ToString("yyyy-MM-dd");
    

    use MM instead mm, mm is for minute & MM is for Month that is why it is taking 01 (default value of MM).

    0 讨论(0)
  • 2020-12-17 01:22

    try this: DateTime.ParseExact("20070205", "yyyyMMdd", null).ToString("yyyy-MM-dd")

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