0

I receive a string in this format "7:00 am - 11:00 pm" representing start and end time. The string will always have two times. Now I need to format that to today's date & time so in above case it's easy. It comes to 18th March 7 AM - 18th March 11 PM but there is an edge case where time is like "7:00 am - 12:00 am", in this case it will need to be converted to 18th March 7 AM - 19th March 12 AM.

Now I can handle this using if :D. So whenever the second token is smaller than first token (e.g. "7:00 am - 02:00 am") I can increase the date of the second part.

string input = "7:00 am - 12:00 am";
List<DateTime> tokens = input.Split('-').Select(x => DateTime.Parse(x.Trim(), CultureInfo.GetCultureInfo("en-NZ"))).ToList();
if(tokens[1] < tokens[0]){
    tokens[1] = tokens[1].AddDays(1);   
}

enter image description here

But I would like to know if there is any builtin way in C# itself through Timespan, Datetime classes etc to handle it.

3
  • Will you always have pairs of times, or could the input be just "7:00 am"?
    – trashr0x
    Mar 17, 2019 at 22:57
  • Yes always pair of times - so two of them - start and finish. Mar 17, 2019 at 22:59
  • There isn't any built-in method to check for overlapping days
    – Jack Le
    Mar 17, 2019 at 23:02

1 Answer 1

3

The code is okay for the requirements you have listed, you could consider hiding some of the logic away by creating an extension method and using DateTime.Hour in your if statement:

public static class StringExtensions
{
    public static IEnumerable<DateTime> ToDateTimePairs(this string input)
    {
        var dates = input.Split('-').Select(x => DateTime.Parse(x.Trim(), CultureInfo.GetCultureInfo("en-NZ"))).ToList();           

        if (dates[1].Hour < dates[0].Hour)
        {
            dates[1] = dates[1].AddDays(1);
        }

        return dates;
    }
}

Your code then becomes:

string input = "7:00 am - 12:00 am";
var dates = input.ToDateTimePairs();
foreach(var date in dates)
{
    Console.WriteLine(date);
}
Console.ReadKey();

Aside: You could also add some validation steps in ToDateTimePairs() (you should only have two valid DateTime objects after splitting the string, etc). The way you implement it is up to you; right now, if an invalid date is contained in the string, the call to DateTime.Parse() will throw a FormatException - if you'd like to handle the validation of the parsing yourself, consider using DateTime.TryParse() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.