PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How to check if a string value is in a correct time format?

 July 30, 2022     c#, string, time, validation     No comments   

Issue

Is there a possibility to check wether a string is in a valid time format or not?

Examples:
12:33:25 --> valid
03:04:05 --> valid
3:4:5    --> valid
25:60:60 --> invalid

Solution

Additional method can be written for the purpose of the string time format validation. TimeSpan structure has got TryParse method which will try to parse a string as TimeSpan and return the outcome of parsing (whether it succeeded or not).

Normal method:

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

Extension method (must be in separate non-generic static class):

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

Calling the methods for the existing string input; (lets imagine it's initialized with some value).

Normal method:

var isValid = IsValidTimeFormat(input);

Extension method:

var isValid = DateTimeExtensions.IsValidTimeFormat(input);

or

var isValid = input.IsValidTimeFormat();


UPDATE: .NET Framework 4.7

Since the release of .NET Framework 4.7, it can be written a little bit cleaner because output parameters can now be declared within a method call. Method calls remain the same as before.

Normal method:

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

Extension method (must be in separate non-generic static class):

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


Answered By - msmolcic
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing