如何检查时间是否是第二天

时间:2016-04-15 06:38:03

标签: c# .net

我有一个Windows应用程序,用户输入开始时间和结束时间,如何检查结束时间是否是第二天。

example: start time           end time
          1:00:00 AM          5:00:00 AM
          5:00:00 AM          10:00:00 AM
          10:00:00 AM          5:00:00 PM
          5:00:00 PM          10:00:00 PM
          10:00:00 PM          1:00:00 AM --(next day)
          1:00:00 AM          5:00:00 AM

我正在尝试以下内容:

private void GenerateReportWithStartTimeandEndTime(string StartTime, string EndTime, string DailyTime)
{
    DateTime tempStartTime = DateTime.ParseExact(StartTime, "HH:mm:ss tt", CultureInfo.InvariantCulture);
    DateTime tempEndTime = DateTime.ParseExact(EndTime, "HH:mm:ss tt", CultureInfo.InvariantCulture);

    DateTime midNightToday = DateTime.Today.AddDays(1);
    var StarthourDifference = (midNightToday - tempStartTime).TotalHours;
    var EndhourDifference = (midNightToday - tempEndTime).TotalHours;
    if (StarthourDifference - EndhourDifference > 0)
    {

    }
    else
    {

    }
}

3 个答案:

答案 0 :(得分:4)

怎么样

bool IsNextDay = EndTime < StartTime;

代码:

//case 1
TimeSpan StartTime = DateTime.ParseExact("5:00:00 PM", "h:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay;
TimeSpan EndTime = DateTime.ParseExact("10:00:00 PM", "h:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay;
bool IsNextDay = EndTime < StartTime; //false

//case 2
TimeSpan StartTime2 = DateTime.ParseExact("10:00:00 PM", "h:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay;
TimeSpan EndTime2 = DateTime.ParseExact("1:00:00 AM", "h:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay;
bool IsNextDay2 = EndTime2 < StartTime2; //true

答案 1 :(得分:0)

这很好用:

对于第二天的时间(因为差异总是5小时),如果hh:mm:ss tt格式的结束解析时间少于开始解析时间,那么它是第二天的时间。

var t1 = "10:00:00 PM";
var t2 = "01:00:00 AM";

var time1 = DateTime.ParseExact(t1, "hh:mm:ss tt", CultureInfo.InvariantCulture);
var time2 = DateTime.ParseExact(t2, "hh:mm:ss tt", CultureInfo.InvariantCulture);

if (time2 < time1)
{
    Console.WriteLine("next day");
}
else
{
    Console.WriteLine("same day");
}

答案 2 :(得分:0)

你需要这样的条件:(startDate&gt; EndDate)和 (EndDate - startDate)&gt; 24小时