Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact string format exception

I am trying to convert a string into datetime with the following C# code,

DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);

eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.

What string format should I use to support both 01/01/2010 and 1/1/2010?

like image 307
Nevin Mathai Avatar asked Jan 04 '10 16:01

Nevin Mathai


People also ask

How to use DateTime ParseExact in 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.

What is DateTime parse exception?

Class DateTimeParseExceptionAn exception thrown when an error occurs during parsing. This exception includes the text being parsed and the error index. Implementation Requirements: This class is intended for use in a single thread.


1 Answers

Using the following date format expression will allow you to use either single or double digit day and month elements.

"M/d/yyyy"

Note that the capital M is significant - a lower case m is the placeholder for minutes.

You will find more information related to date format strings here.

You can use the following Powershell command to test them.

[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)
like image 141
Scott Munro Avatar answered Oct 05 '22 13:10

Scott Munro