[c#] Datetime format Issue: String was not recognized as a valid DateTime

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"

I tried Convert.ToDateTime() function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.

I tried DateTime.ParseExact() function also, But getting Exception.

I am getting error:

String was not recognized as a valid DateTime.

This question is related to c# asp.net datetime

The answer is


This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.

So first split it by slash

var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2] 


var properFormat = month + "/" +day +"/" + year;

Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.


Below code worked for me:

string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);

try this:

string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",  
   System.Globalization.CultureInfo.InvariantCulture, 
   System.Globalization.DateTimeStyles.None, out dtTime))
 {
    Console.WriteLine(dtTime);
 }

You can use DateTime.ParseExact() method.

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.

DateTime date = DateTime.ParseExact("04/30/2013 23:00", 
                                    "MM/dd/yyyy HH:mm", 
                                    CultureInfo.InvariantCulture);

Here is a DEMO.

hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.

For more information, check Custom Date and Time Format Strings


You may use this type format (get formatted data from sql server)


FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')


CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)


DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",  
                                           CultureInfo.InvariantCulture);

Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).


change the culture and try out like this might work for you

string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00", 
     formats, new CultureInfo("en-US"), DateTimeStyles.None);

Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?