I made a Fiddle , but before using it, it is important to explain some aspects.
First, it's important to note that passing% s of schedules is not exactly best practice, especially since you'll need to mount dates within the role. Initially I made an optimistic implementation, as follows:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public static IEnumerable<DateTime> OcorrenciasDeHorarios(
DateTime Inicio, DateTime Final, params string[] Horarios)
{
var cultura = new CultureInfo("en-US");
for (var dia = Inicio; dia <= Final; dia = dia.AddDays(1))
{
foreach (var diaHorario in Horarios.Select(h => DateTime.Parse(dia.Date.ToString("MM/dd/yyyy") + " " + h)))
{
if (diaHorario >= Inicio && diaHorario <= Final)
yield return diaHorario;
}
}
}
Second, notice that I did not string
. TimeSpan
is not a data structure that supports time zones . I used TimeSpan
myself, just joining the list of times with the dates you want to evaluate.
Notice that I changed DateTime
to int
because I'm interested to know what the results were. Once that's done, I can do the following:
var lista = OcorrenciasDeHorarios(DateTime.Parse("2017-01-10 01:35:00 PM"), DateTime.Parse("2017-01-12 07:35:00 PM"), "12:50:00 AM", "05:50:00 PM");
Console.WriteLine(lista.Count());
foreach (var item in lista)
Console.WriteLine(item);
Returns 5 occurrences ( IEnumerable<DateTime>
) and prints the list of hours with the possible times just below.
Now, let's assume that this input depends on a user. We will have to make a pessimistic algorithm, which would look like this:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public static IEnumerable<DateTime> OcorrenciasDeHorarios(
DateTime Inicio, DateTime Final, params string[] Horarios)
{
var cultura = new CultureInfo("en-US");
for (var dia = Inicio; dia <= Final; dia = dia.AddDays(1))
{
foreach (var diaHorario in Horarios)
{
DateTime teste = DateTime.MinValue;
if (!DateTime.TryParse(dia.Date.ToString("MM/dd/yyyy") + " " + diaHorario, out teste))
{
Console.WriteLine("Horário " + diaHorario + " está em formato inadequado e não será considerado.");
continue;
}
if (teste >= Inicio && teste <= Final)
yield return teste;
}
}
}
Here's another Fiddle here .