Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to a date in .net

Tags:

c#

.net

I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?

like image 367
JoshL Avatar asked Sep 23 '08 19:09

JoshL


People also ask

Is there a date type in C#?

To set dates in C#, use DateTime class. The DateTime value is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.

What is ParseExact C#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.


3 Answers

string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);

or

DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);

More info in the MSDN documentation on ParseExact and TryParseExact.

like image 192
Paul van Brenk Avatar answered Sep 19 '22 17:09

Paul van Brenk


you could try also TryParseExact for set exact format. method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx

e.g.

DateTime outDt;
bool blnYYYMMDD = 
     DateTime.TryParseExact(yourString,"yyyyMMdd"
                            ,CultureInfo.CurrentCulture,DateTimeStyles.None
                            , out outDt);

I hope i help you.

like image 32
stefano m Avatar answered Sep 21 '22 17:09

stefano m


DateTime.TryParse method

like image 45
Steven A. Lowe Avatar answered Sep 18 '22 17:09

Steven A. Lowe