C # - regular expression confirming date and time

I get date and time from CSV file

The received Date format is  YYYYMMDD (string) (there is no ":" ,"-","/" to 
separate  Year month and date).

The received time format is HH:MM (24 Hour clock).

I need to check both options so that (example) (i) 000011990 can be invalidated on date (ii) 77:90 can be invalid for time.

Question:

A regular expression is the right candidate for this (or) is there any other way to achieve this?

+3
source share
4 answers

You are looking for DateTime.TryParseExact:

string source = ...;
DateTime date;
if (!DateTime.TryParseExact(source, 
                            "yyyyMMdd", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None, 
                            out date)) {
    //Error!
}

You can use the same code to check the time with a format string "HH:mm".

+9
source

The easiest solution is to use

DateTime output;
if(!DateTime.TryParse(yourstring, out output))
{ 
   // string is not a valid DateTime format
}

DateTime.TryParse DateTime, , - , false, DateTime.

+4

I think the best way is to use the date format class built into C #: DateTime.parse

+2
source

You can use one of the TryParsestructure methods DateTime. They will return false if they are not parsed.

In another option, it uses methods ParseExact, but for them you need to specify a format provider.

+1
source

Source: https://habr.com/ru/post/1740657/


All Articles