Answer the question
In order to leave comments, you need to log in
C# - How can you compare time (DateTime)?
Hello. I am a beginner programmer. The other day I ran into a problem: How to compare time? For example, I take the present time (DateTime.Now) and want to compare it with a specific time that I need, for example:
It's 11:44 am, and I need to find out: am I in the time interval between 11:30 and 12:30, and how much time remaining (if any) until the end of the interval. How can this be implemented? I will be glad for any help)
Answer the question
In order to leave comments, you need to log in
var periodFrom = new DateTime(2017, 10, 5, 11, 30, 0);
var periodTo = new DateTime(2017, 10, 5, 12, 30, 0);
var periodNow = DateTime.Now;
if (periodNow > periodFrom && periodNow < periodTo)
{
Console.WriteLine("between");
}
else
{
Console.WriteLine("not between");
}
// timeFrom и timeTo выбирай вариант какой нужен
var timeFrom = periodFrom.TimeOfDay;
var timeTo = periodTo.TimeOfDay;
var timeFrom1 = new TimeSpan(11, 30, 0);
var timeTo1 = new TimeSpan(12, 30, 0);
var timeNow = DateTime.Now.TimeOfDay;
if (timeNow > timeFrom1 && timeNow < timeTo1)
{
Console.WriteLine("between");
}
else
{
Console.WriteLine("not between");
}
In Sharpe, date-time can be compared by greater than/less than/equal to in the same way as regular numbers.
In Sharpe, a date-time can be subtracted from another date-time using the Subtract() method, resulting in a TimeSpan https://msdn.microsoft.com/en-us/library/8ysw4sby(...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question