Convert Date String to another Date string with different format

前端 未结 4 1449
不思量自难忘°
不思量自难忘° 2021-01-18 21:45

I need to convert an string date with format yyyyMMdd to a date string with format MM/dd/yyyy. Which is the best to do it?

I\'m doing this:

4条回答
  •  甜味超标
    2021-01-18 22:32

    What you are doing is fine.

    Probably you can improve it by using DateTime.TryParseExact and on successful parsing, format the DateTime object in other format.

    string dateString = "20130916";
    DateTime parsedDateTime;
    string formattedDate;
    if(DateTime.TryParseExact(dateString, "yyyyMMdd", 
                        CultureInfo.InvariantCulture, 
                        DateTimeStyles.None, 
                        out parsedDateTime))
    {
        formattedDate = parsedDateTime.ToString("MM/dd/yyyy");
    }
    else
    {
           Console.WriteLine("Parsing failed");
    }
    

提交回复
热议问题