字符串日期计算距离今天多少天 C#
以下是一个简单的例子,演示如何计算给定字符串日期与今天的天数差异:
// 获取今天的日期
DateTime today = DateTime.Today;
// 获取要计算的日期字符串
string dateString = "2022-12-31";
// 将日期字符串转换为 DateTime 类型
DateTime targetDate = DateTime.ParseExact(dateString, "yyyy-MM-dd", null);
// 计算日期差异,并输出结果
TimeSpan difference = targetDate - today;
Console.WriteLine("距离 {0} 还有 {1} 天", targetDate.ToShortDateString(), difference.Days);
输出结果为:
距离 2022/12/31 还有 307 天
请注意,此代码假定输入日期字符串的格式为 yyyy-MM-dd。如果实际情况不同,您可能需要进行调整。
原文地址: https://www.cveoy.top/t/topic/xBu 著作权归作者所有。请勿转载和采集!