在我的 C # 应用程序中,我传递了一个字符串变量,它的格式为 yyyymmdd-yyyyymmdd,表示一个 from 和 to 日期。我想分别得到这些日期的开始和结束时间。目前我有下面的代码,但想知道是否有更多的优雅的解决方案?
因此,对于 pdr = 20090521-20090523,将得到“2009052100:00:00”和“2009052323:59:59”
private void ValidateDatePeriod(string pdr, out DateTime startDate,
out DateTime endDate)
{
string[] dates = pdr.Split('-');
if (dates.Length != 2)
{
throw new Exception("Date period is of incorrect format");
}
if (dates[0].Length != 8 || dates[1].Length != 8)
{
throw new Exception("Split date periods are of incorrect format");
}
startDate = DateTime.ParseExact(dates[0] + " 00:00:00",
"yyyyMMdd HH:mm:ss", null);
endDate = DateTime.ParseExact(dates[1] + "23:59:59",
"yyyyMMdd HH::mm:ss", null);
}