我正在使用一个System.DateTime对象来允许用户选择日期范围.用户只能使用第三方日历选择日期(而不是时间),因此我需要在日期之后自动指定应该使用的时间(即:00:00:00或23:59:59)被选中.
如何指定日期选择器已将日期存储为DateTime对象后的时间?我可以使用这些AddHours, AddMinutes, AddSeconds方法,但这些方法与当前时间相关,可能不是00:00:00.
在startDate将需要有时间是00:00:00,并endDate有一23:59:59时间占到整个天.
在我的C#应用程序中,我传递一个格式为yyyymmdd-yyyymmdd的字符串变量,它表示来自和迄今.我想分别得到这些日期的开始和结束时间.目前我有以下代码,但想知道是否有更优雅的解决方案?
所以对于pdr = 20090521-20090523会得到"20090521 00:00:00"和"20090523 23: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);
}
Run Code Online (Sandbox Code Playgroud)