获取日期的最长时间

时间:2011-11-29 23:27:46

标签: c#

如何获取从datetimepicker中选择的DateTime值的最长时间? 例如'08 / 21/2011 23:59:59'

3 个答案:

答案 0 :(得分:15)

myDateTime.AddDays(1).Date.AddSeconds(-1)

<强>更新 根据@RenatoGama关于这个问题的评论:

特定于结束日期方案的一个可能的其他答案是myDateTime.Date.AddDays(1)。在第二天到达结束日期时,使用<代替<=(如dateTocheck < endDate.Date.AddDays(1)中所示)。

样品:

'08/21/2011 13:03:59' -> .AddDays(1)     -> '08/22/2011 13:03:59' 

'08/22/2011 13:03:59' -> .Date           -> '08/22/2011 00:00:00'  

'08/22/2011 00:00:00' -> .AddSeconds(-1) -> '08/21/2011 23:59:59'
// OR
'08/22/2011 00:00:00' -> .AddTicks(-1)   -> '08/21/2011 23:59:59'
// Note: A tick is the smallest unit for time difference that DateTime can detect
// So, technically more accurate answer than using seconds -- Thanks @aron

注:AFAIK,'08 / 22/2011'== '08 / 22/2011 00:00:00'

答案 1 :(得分:2)

minimun

  

&#39; 08/21/2011 00:00:00&#39;

最大化

  

&#39; 08/21/2011 23:59:59&#39;

<强>用法:

   var firstDate = dtpFrom.Value.Date; //  0:00:00
   var secondDate =  dtpTo.Value.Date.AddSeconds(86400 - 1); //23:59:59 - 86400 is 24 hours
   var list = Services.GetListForFilter(firstDate, secondDate);

答案 2 :(得分:2)

DateTime d = new DateTime(2017, 1, 13);
//d= 13/1/2017 12:00:00 AM
d = d.Add(DateTime.MaxValue.TimeOfDay);
//d= 13/1/2017 11:59:59 PM