How to convert string to DateTime in C #?

is it possible to convert a string (date stored as varchar in the database) to datetime in C #?

eg. I have a table that stores dates as varchar and it stores values ​​as an example

01/21/14 11:42:36 PM

I want to get the result in the format yyyy-mm-dd

I tried,

 CultureInfo enUS = new CultureInfo("en-US"); DateTime d; DateTime.TryParseExact("01/21/14 11:42:36 PM", "yyyy-mm-dd", enUS, DateTimeStyles.None, out d); 

also tried to follow these steps:

 CultureInfo enUS = new CultureInfo("en-US"); DateTime d = Convert.ToDateTime("01/21/14 11:42:36 PM"); string dt = Convert.ToString(d); DateTime.TryParseExact(dt, "MM/dd/yy hh:mm:ss tt", enUS, DateTimeStyles.None, out d); var output = d.ToString("yyyy-mm-dd"); 

get the value 1/1/0001 12:00.. in dt .

what could be the reason? also in what format do I need to transfer the date ( dt in the above case) to DateTime.TryParseExact(..)

+4
c # sql datetime sql-server-2008 converter
Feb 05 '14 at 10:25
source share
2 answers

The second parameter of your call should be in the format you are passing. After creating the datetime, you can specify the output format:

 CultureInfo enUS = new CultureInfo("en-US"); DateTime d; DateTime.TryParseExact("01/21/14 11:42:36 PM", "MM/dd/yy hh:mm:ss tt", enUS, DateTimeStyles.None, out d); var output = d.ToString("yyyy-MM-dd"); 
+5
Feb 05 '14 at 10:28
source share
  String date = "01/21/14 11:42:36 PM"; DateTime dt = Convert.ToDateTime(date); var output = dt.ToString("yyyy-MM-dd"); 
0
Feb 06 '14 at 8:11
source share



All Articles