Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
Priya Avatar asked Apr 15 '13 11:04

Priya


4 Answers

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:

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

See here for more information:

Custom Date and Time Format Strings

like image 187
Botz3000 Avatar answered Oct 21 '22 04:10

Botz3000


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

like image 38
Soner Gönül Avatar answered Oct 21 '22 03:10

Soner Gönül


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);
 }
like image 20
Arshad Avatar answered Oct 21 '22 03:10

Arshad


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.

like image 23
Manjay_TBAG Avatar answered Oct 21 '22 04:10

Manjay_TBAG