Skip to content

Commit

Permalink
Merge pull request joaomatossilva#212 from Rekha-Reddyshetty/feature/…
Browse files Browse the repository at this point in the history
…business-hours

Feature: Add Business Hours Check Extension Method
  • Loading branch information
joaomatossilva authored Nov 21, 2024
2 parents 9026e2f + 96ffc7f commit 81b8785
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/DateTimeExtensions/BusinessHoursExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;

namespace DateTimeExtensions
{
public static class BusinessHoursExtensions
{
/// <summary>
/// This method helps determine if a given time is during standard working hours.
/// </summary>
/// <param name="startTime">Start time of the business hours.</param>
/// <param name="endTime">End time of the business hours.</param>
/// <returns>If given time is during business hours, method returns true else it returns false.</returns>
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;
}
}
}
}
38 changes: 38 additions & 0 deletions tests/DateTimeExtensions.Tests/BusinessHoursTests.cs
Original file line number Diff line number Diff line change
@@ -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));
}
}
}

0 comments on commit 81b8785

Please sign in to comment.