The string was not recognized as valid DateTime (formatting)

I am trying to convert an Oracle DateTime field to a string ( TextBox ). However, I keep getting the following error:

The string was not recognized as a valid DateTime.

Value in the field: 7/25/2013 4:12:18 PM

code:

 DateTime dt = DateTime.ParseExact("MM/dd/yyyy HH:mm:ss tt",dr["category"].ToString().Trim(), CultureInfo.InvariantCulture); txtFedCat.Text = dt.ToString("dd/M/yyyy"); 
+4
source share
3 answers

Try the following:

 DateTime dt = DateTime.ParseExact(dr["category"].ToString().Trim(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); 

The first parameter of ParseExact is the date string, and the second is the format. You had the opposite. I also think that you want to use the following format specifiers:

  • M: month, from 1 to 12.
  • d: day of the month, from 1 to 31.
  • h: hour using a 12-hour clock from 1 to 12.
+3
source
 var dateString = "7/25/2013 4:12:18 PM"; DateTime dt = DateTime.ParseExact(dateString, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); var txtFedCat = dt.ToString("dd/M/yyyy"); 
+1
source

You can do it:

 string strDate = DateTime.ParseExact(yourDateTime, "M/d/yyyy h:mm:ss tt", null).ToString(); if (strDate.Substring(0, 10).Trim().LastIndexOf(" ", System.StringComparison.Ordinal) == 8) strDate = strDate.Substring(0, 8).Trim(); else strDate = strDate.Substring(0, 10).Trim(); DateTime FinalDate = Convert.ToDateTime(strDate); 
0
source

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


All Articles