如何将日期格式从yyyy/MM/dd转为dd/MM/yyyy?C#代码修改位置咨询
解决C#日期格式转换问题
你需要在输出阶段对DateTime对象指定格式,DateTime本身是无格式的,格式只在转为字符串显示时生效,这就是你之前尝试无效的原因。
正确修改步骤:
- 保留你已经转换好的
dateBorrowedDateTime和dateReturnedDateTime对象 - 在
Console.WriteLine中,把原来的detail[2]和detail[3](原始字符串)替换成这两个DateTime对象的格式化输出
修改后的Console.WriteLine代码:
Console.WriteLine("{0,10} {1,15} {2,15} {3,15} {4, 10} {5, 10} {6, 10}", detail[0], detail[1], dateBorrowedDateTime.ToString("dd/MM/yyyy"), dateReturnedDateTime.ToString("dd/MM/yyyy"), daysLoan, "", "");
额外优化建议:
因为你明确知道CSV里的日期格式是yyyy/MM/dd,建议用DateTime.ParseExact来转换,避免系统区域设置差异导致转换失败(这可能是你之前转换后加代码出错的诱因):
DateTime dateBorrowedDateTime = DateTime.ParseExact(dateBorrowed, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); DateTime dateReturnedDateTime = DateTime.ParseExact(dateReturned, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture);
记得要引用System.Globalization命名空间。
完整修改后的代码片段:
using (StreamReader sr = new StreamReader("loaninfo.csv")) { string? s = sr.ReadLine(); // read the heading // display the heading if (s != null) { string[] heading = s.Split(','); Console.WriteLine("{0,10} {1,15} {2,15} {3,15} {4, 10} {5, 10} {6, 10}", heading[0], heading[1], heading[2], heading[3], "Days loan", "Days overdue", "Fine"); // repeat until end of file } while ((s = sr.ReadLine()) != null) { string[] detail = s.Split(','); string dateBorrowed = detail[2]; string dateReturned = detail[3]; // 按指定格式解析日期,避免区域差异问题 DateTime dateBorrowedDateTime = DateTime.ParseExact(dateBorrowed, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); DateTime dateReturnedDateTime = DateTime.ParseExact(dateReturned, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); int daysLoan = dateReturnedDateTime.Subtract(dateBorrowedDateTime).Days; // 输出时指定目标日期格式 Console.WriteLine("{0,10} {1,15} {2,15} {3,15} {4, 10} {5, 10} {6, 10}", detail[0], detail[1], dateBorrowedDateTime.ToString("dd/MM/yyyy"), dateReturnedDateTime.ToString("dd/MM/yyyy"), daysLoan, "", ""); } }
内容的提问来源于stack exchange,提问作者donut
相关产品推荐
相关产品推荐

