Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

c# 4.0 - C# Compare Time between Two Time Intervals

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

Times to compare:

00:00:00 and 01:00:00

Any help will be appreciated.

Updated Question:

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:

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. Between Date Range :2012-01-01 to 2012-31
  2. Between Time Range above.

And apply $ Rate accordingly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...