C#比较两个时间间隔之间的时间 [英] C# Compare Time between Two Time Intervals

查看:1210
本文介绍了C#比较两个时间间隔之间的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试比较两次之间的给定时间,看看是否在这些时间间隔内。例如如果给定时间是00:00,我需要知道它是否在21:00:00到7:00:00之间。 Tried TimeSpan.Compare没有锁,也使用>或<时间部分。

Trying to compare a given Time between two times to see if it's within the those intervals. e.g. if given Time is 00:00 I need to find out if it falls between 21:00:00 to 7:00:00. Tried TimeSpan.Compare no lock and also used > or < for Time Part.

例如。
给定间隔:

e.g. Given Intervals:


7:00:00 to 19:00:00
19:00:00 to 21:00:00
21:00:00 to 7:00:00


比较次数:


00:00:00和01: 00:00

00:00:00 and 01:00:00

任何帮助将不胜感激。

Any help will be appreciated.

更新的问题:

看起来像要求是安静的。要求是基本上通过时间(TimeSpan),并与两个TimeSpan间隔进行比较,看看它们是否落入那些间隔。

Looks like the requirement is quiet vague. The requirement is basically to pass the Time (TimeSpan) and compare with two TimeSpan intervals to see if they fall in to the those interval.

假设如果员工在以下不同时段工作,员工会获得不同的津贴:

e.g. Lets say employees get different allowances if they work on different time slots below:


日期范围:2012-01-01至2012-31

Date Range: 2012-01-01 to 2012-31

19:00:00 to 21:00:00 ($10.00)
21:00:00 to 7:00:00 ($11.00)
7:00:00 to 19:00:00 ($12.00)


要计算员工的每小时工资率,我需要检查员工是否工作

To calculate the hourly rate for an employee I need to check whether the employee has worked



  1. 介于日期范围之间:2012-01-01至2012-31

  2. 在上述时间范围之间。


然后应用$ Rate。

And apply $ Rate accordingly.

推荐答案

youself一个扩展方法如:

You could write youself an extension method like;

public static class TimeExtensions
{
    public static bool IsBetween(this DateTime time, DateTime startTime, DateTime endTime)
    {
        if (time.TimeOfDay == startTime.TimeOfDay) return true;
        if (time.TimeOfDay == endTime.TimeOfDay) return true;

        if (startTime.TimeOfDay <= endTime.TimeOfDay)
            return (time.TimeOfDay >= startTime.TimeOfDay && time.TimeOfDay <= endTime.TimeOfDay);
        else
            return !(time.TimeOfDay >= endTime.TimeOfDay && time.TimeOfDay <= startTime.TimeOfDay);
    }
}

这篇关于C#比较两个时间间隔之间的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆