Convert 20121004 (yyyyMMdd) to a valid date time?

前端 未结 4 1261
被撕碎了的回忆
被撕碎了的回忆 2020-12-25 09:32

I have a string in the following format yyyyMMdd and I am trying to get it to look like this:

yyyy-MM-dd

When I try:



        
4条回答
  •  粉色の甜心
    2020-12-25 09:57

    Just use the DateTime.ParseExact method:

    string date = "20121004";
    
    string result = DateTime.ParseExact(date, "yyyyMMdd",
                    CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
    

    This also provides the advantage of validating the date before reformatting it with the hyphens. ParseExact throws an exception you can catch, if the date is not in valid range, or the format does not match.

提交回复
热议问题