Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Determine if a string of format "hh:mm" is valid date

I’m learning C# and I’m taking an Udemy course. There is this exercise:

Given an user input of the following form hh:mm, determine it’s a valid date.
19:20 or 01:20 are valid inputs, but 24:01 is not.

I implemented it by working on chars but I believe I’m complicating myself. Is there an alternative(besides regex) ? (maybe using some .net builtins(DateTime/Timespan)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        Console.Write("Enter a time value(ex: 19:20): ");
        var result = "Valid time";
        var input = Console.ReadLine();
        if (String.IsNullOrEmpty(input)) {
            Console.WriteLine("Invalid time");
            Environment.Exit(-1);
        }
        var dates = input.Split(":");

        //validate hour
        var firstDigitHour = (int)char.GetNumericValue(dates[0][0]);
        var secondDigitHour = (int)char.GetNumericValue(dates[0][1]);
        var hour = 10 * firstDigitHour + secondDigitHour;
        if (hour > 23) {
            result = "Invalid time";
        }

        //validate minutes
        var firstDigitMinute = (int)char.GetNumericValue(dates[1][0]);
        var secondDigitMinute = (int)char.GetNumericValue(dates[1][1]);
        var minutes = 10 * firstDigitMinute + secondDigitMinute;
        if (minutes > 59 ) {
            result = "Invalid time";
        }


        Console.WriteLine(result);

>Solution :

You can do something like this:

public static bool IsValidTimeFormat(string input)
{
    TimeSpan dummyOutput;
    return TimeSpan.TryParse(input, out dummyOutput);
}

And try out:

string yourString = "19:20";
string yourString2 = "24:48";
Console.WriteLine(IsValidTimeFormat(yourString).ToString()); //will print True
Console.WriteLine(IsValidTimeFormat(yourString2).ToString()); //will print False
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading