diff --git a/src/DateTimeExtensions/BusinessHoursExtensions.cs b/src/DateTimeExtensions/BusinessHoursExtensions.cs new file mode 100644 index 0000000..677df22 --- /dev/null +++ b/src/DateTimeExtensions/BusinessHoursExtensions.cs @@ -0,0 +1,28 @@ +using System; + +namespace DateTimeExtensions +{ + public static class BusinessHoursExtensions + { + /// + /// This method helps determine if a given time is during standard working hours. + /// + /// Start time of the business hours. + /// End time of the business hours. + /// If given time is during business hours, method returns true else it returns false. + public static bool IsWithinBusinessHours(this DateTime dateTime, TimeSpan startTime, TimeSpan endTime) + { + var currentTime = dateTime.TimeOfDay; + //if startTime is less than endTime (ex:Business hours from 9AM to 5PM) + if (startTime <= endTime) + { + return currentTime >= startTime && currentTime <= endTime; + } + //if startTime is greater than endTime (ex:Business hours from 9PM to 5AM) + else + { + return currentTime >= startTime || currentTime <= endTime; + } + } + } +} diff --git a/tests/DateTimeExtensions.Tests/BusinessHoursTests.cs b/tests/DateTimeExtensions.Tests/BusinessHoursTests.cs new file mode 100644 index 0000000..1d4e705 --- /dev/null +++ b/tests/DateTimeExtensions.Tests/BusinessHoursTests.cs @@ -0,0 +1,38 @@ +using System; +using NUnit.Framework; +using DateTimeExtensions; + +namespace DateTimeExtensions.Tests +{ + [TestFixture] + public class BusinessHoursTests + { + [Test] + public void check_is_within_regular_business_hours() + { + //Business hours are from 9AM to 5PM + var startTime = new TimeSpan(9, 0, 0); // 9 AM + var endTime = new TimeSpan(17, 0, 0); // 5 PM + + var withinHoursDate = new DateTime(2024, 11, 12, 10, 30, 0); // 10:30 AM + Assert.IsTrue(withinHoursDate.IsWithinBusinessHours(startTime, endTime)); + + var outsideHoursDate = new DateTime(2024, 11, 12, 18, 22, 0); // 6:22 PM + Assert.IsFalse(outsideHoursDate.IsWithinBusinessHours(startTime, endTime)); + } + + [Test] + public void check_is_within_overnight_business_hours() + { + //Business hours are from 9AM to 5PM + var startTime = new TimeSpan(19, 0, 0); // 9 AM + var endTime = new TimeSpan(5, 0, 0); // 5 PM + + var withinHoursDate = new DateTime(2024, 11, 12, 22, 0, 20); // 10:00:20 PM + Assert.IsTrue(withinHoursDate.IsWithinBusinessHours(startTime, endTime)); + + var outsideHoursDate = new DateTime(2024, 11, 12, 12, 30, 44); // 12:30:44 PM + Assert.IsFalse(outsideHoursDate.IsWithinBusinessHours(startTime, endTime)); + } + } +}