A
A
artemkaw2017-10-05 18:33:37
Programming
artemkaw, 2017-10-05 18:33:37

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

2 answer(s)
E
eRKa, 2017-10-05
@artemkaw

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

A
Arkadiy Parinov, 2017-10-05
@Young_khv

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 question

Ask a Question

731 491 924 answers to any question