報錯原因:因為日期串無法正常轉換。
解決代碼:
class Program { static void Main(string[] args) { //1、正確的寫法(不帶符號的日期串轉換通用日期格式,formatDate輸出結果是:2021-10-11) IFormatProvider ifp = new CultureInfo("zh-CN", true); string formatDate = DateTime.ParseExact("20211011", "yyyyMMdd", ifp).ToString("yyyy-MM-dd"); Console.WriteLine(formatDate); Console.ReadKey(); } }