Encontrar se o tempo atual cai em um intervalo de tempo
Pergunta
Usando NET 3.5
Eu quero determinar se a hora atual cai em um intervalo de tempo.
Até agora eu tenho a currentime:
DateTime currentTime = new DateTime();
currentTime.TimeOfDay;
Eu estou apagando sobre como obter o intervalo de tempo convertido e comparados. Será que este trabalho?
if (Convert.ToDateTime("11:59") <= currentTime.TimeOfDay
&& Convert.ToDateTime("13:01") >= currentTime.TimeOfDay)
{
//match found
}
Update1: Obrigado a todos por suas sugestões. Eu não estava familiarizado com a função TimeSpan.
Solução
Para a verificação de um tempo de uso diário:
TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > start) && (now < end))
{
//match found
}
Por vezes absolutos usar:
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
Outras dicas
Algumas boas respostas aqui, mas a cobertura nenhum o caso de seu tempo começar a ser em um dia diferente do que o seu tempo final. Se você precisa para ficar em cima do dia limite, em seguida, algo como isto pode ajudar:
TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00"); // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;
if (start <= end)
{
// start and stop times are in the same day
if (now >= start && now <= end)
{
// current time is between start and stop
}
}
else
{
// start and stop times are in different days
if (now >= start || now <= end)
{
// current time is between start and stop
}
}
Note que neste exemplo os limites de tempo são inclusivas e que este ainda assume isto menos de uma diferença de 24 horas entre start
e stop
.
if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >= currentTime.TimeOfDay)
{
//match found
}
Se você realmente deseja analisar uma seqüência em um TimeSpan, então você pode usar:
TimeSpan start = TimeSpan.Parse("11:59");
TimeSpan end = TimeSpan.Parse("13:01");
A função de extensão pouco simples para isso:
public static bool IsBetween(this DateTime now, TimeSpan start, TimeSpan end)
{
var time = now.TimeOfDay;
// If the start time and the end time is in the same day.
if (start <= end)
return time >= start && time <= end;
// The start time and end time is on different days.
return time >= start || time <= end;
}
Tente usar o objeto TimeRange em C # para completar seu objetivo.
TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");
bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);
A propriedade TimeOfDay
retorna um TimeSpan
valor.
Tente o seguinte código:
TimeSpan time = DateTime.Now.TimeOfDay;
if (time > new TimeSpan(11, 59, 00) //Hours, Minutes, Seconds
&& time < new TimeSpan(13, 01, 00)) {
//match found
}
Além disso, new DateTime()
é o mesmo que DateTime.MinValue
e será sempre igual a 1/1/0001 12:00:00 AM
. (Tipos de valor não pode ter valores padrão não vazios) Você quer usar DateTime.Now
.
Você está muito perto, o problema é que você está comparando um DateTime a uma TimeOfDay. O que você precisa fazer é adicionar a propriedade .TimeOfDay ao final do seu Convert.ToDateTime () funções.
Este vai ser mais simples para lidar com o caso limite dia? :)
TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00"); // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;
bool bMatched = now.TimeOfDay >= start.TimeOfDay &&
now.TimeOfDay < end.TimeOfDay;
// Handle the boundary case of switching the day across mid-night
if (end < start)
bMatched = !bMatched;
if(bMatched)
{
// match found, current time is between start and end
}
else
{
// otherwise ...
}
Usando Linq podemos simplificar esta por este
Enumerable.Range(0, (int)(to - from).TotalHours + 1)
.Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))
using System;
public class Program
{
public static void Main()
{
TimeSpan t=new TimeSpan(20,00,00);//Time to check
TimeSpan start = new TimeSpan(20, 0, 0); //8 o'clock evening
TimeSpan end = new TimeSpan(08, 0, 0); //8 o'clock Morning
if ((start>=end && (t<end ||t>=start))||(start<end && (t>=start && t<end)))
{
Console.WriteLine("Mached");
}
else
{
Console.WriteLine("Not Mached");
}
}
}