Split DateTime strings when converting

I am writing a C # class that converts strings to dates. Pretty easy, I think. The class accepts a string format as "yyyy-MM-dd" and inputstrings as "2010-10-10"

However, I have some cases that give me problems:

format "yyyyMMdd" input "19950000"

or

format "dd-MM-yyyy" input "00-06-2001"

Note that these cases have zeros ('00') for the day and / or month and that they cannot be converted to DateTime. I need to replace them.

To deal with these cases, I need to split the input string in parts, one per day, month and year, so I can set some days and month by default (maybe 01) if they are missing. But for this I need to use formatstring.

So the question is, how can I split the input string in the components specified in stringstring format?

thank

[UPDATE] , :

string[] formats = { format, format.Replace("dd", "00").Replace("MM", "00"), format.Replace("dd", "00"), format.Replace("MM", "00") };

// Parse input
DateTime d = DateTime.ParseExact(txtDate.Text, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);

('00') , .

!

+3
3

, DateTime.ParseExact, .

// Define all allowed formats
string[] formats =  { "yyyyMMdd", "yyyyMM00", "yyyy0000" };

// Parse input
DateTime d;
d = DateTime.ParseExact("20100930", formats, 
                 CultureInfo.InvariantCulture, DateTimeStyles.None);
d = DateTime.ParseExact("20100900", formats, 
                 CultureInfo.InvariantCulture, DateTimeStyles.None);
d = DateTime.ParseExact("20100000", formats, 
                 CultureInfo.InvariantCulture, DateTimeStyles.None);

/ : 1.

+3

, , , .

, , 0.

Chain of-Respons_pattern: http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

private const string Pattern_dd-mm-yyyy = "(\d\d)-(\d\d)-(\d){4}";
private const string Pattern_ddmmyyyy = "(\d\d)(\d\d)(\d){4}";
private const string Pattern_ddSlashmmSlashyyyy = "(\d\d)/(\d\d)/(\d){4}";
+3

( ), .

, DateTime ParseExact (http://msdn.microsoft.com/en-us/library/w2sa9yss(v=VS.80).aspx), .

: ? , /, , , TryParseExact, .

DateTime, Year, Month Day, ,

+1
source

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


All Articles