How to convert string to a DateTime in C#?

夙愿已清 提交于 2019-12-13 13:27:59

问题


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

eg. i'm having a table which stores dates as varchar and it stores values as 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 below 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");

getting value 1/1/0001 12:00.. in dt.

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


回答1:


The second parameter of your call should be the format you're passing. After the datetime is created 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");



回答2:


            String date = "01/21/14 11:42:36 PM";
            DateTime dt = Convert.ToDateTime(date);
            var output = dt.ToString("yyyy-MM-dd");


来源:https://stackoverflow.com/questions/21574549/how-to-convert-string-to-a-datetime-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!