Created
September 2, 2020 08:49
-
-
Save rofr/ecf81cc51c44c979567760821999aaa7 to your computer and use it in GitHub Desktop.
Programming is hard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void Can_Handle_InTimeSpan() | |
{ | |
var testtime = DateTime.Now; | |
var start = testtime.AddHours(-3); | |
var end = testtime.AddHours(3); | |
Assert.IsTrue(testtime.InTimeSpan(start, end)); | |
} | |
[TestMethod] | |
public void Can_Handle_InTimeSpan_24h() | |
{ | |
var testtime = DateTime.Now; | |
var start = Convert.ToDateTime("1900-01-01 07:00"); | |
var end = Convert.ToDateTime("1900-01-01 07:00"); | |
Assert.IsTrue(testtime.InTimeSpan(start, end)); | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Check if a time is in the span | |
/// Only checks TimeOfDay | |
/// </summary> | |
/// <param name="time">The time to check</param> | |
/// <param name="startTime">Start time</param> | |
/// <param name="endTime">End time</param> | |
/// <returns>True/False</returns> | |
public static bool InTimeSpan(this DateTime time, DateTime startTime, DateTime endTime) | |
{ | |
TimeSpan start = TimeSpan.Parse(startTime.ToString("HH:mm")); // 10 PM | |
TimeSpan end = TimeSpan.Parse(endTime.ToString("HH:mm")); // 2 AM | |
TimeSpan now = time.TimeOfDay; | |
if (start < end) | |
{ | |
// start and stop times are in the same day | |
if (now >= start && now <= end) | |
{ | |
return true; | |
} | |
} | |
else if (start > end) | |
{ | |
// start and stop times are in different days | |
if (now >= start || now <= end) | |
{ | |
return true; | |
} | |
} | |
else | |
{ | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment