如何字符串转换为C#日期时间? [英] How to convert string to a DateTime in C#?
问题描述
有可能到字符串
(日期存储为 VARCHAR
数据库)转换为日期时间
在C#?
is it possible to convert a string
(date stored as varchar
in database) to datetime
in c#?
如。我遇到存储日期为varchar一个表,并将其存储值例如
eg. i'm having a table which stores dates as varchar and it stores values as example
14年1月21日下午11时42分36秒
我想要得到的结果,格式为 YYYY-MM-DD
i want to get the result in the format yyyy-mm-dd
我试过了,
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);
也尝试下面的步骤:
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");
获得价值 1/1/0001 12:00 ..
在 DT
。
可能是什么原因?还以哪种格式做我需要传递的日期( DT
在上述情况下),以 DateTime.TryParseExact(..)
what could be the reason? also in which format do i need to pass the date (dt
in above case) to DateTime.TryParseExact(..)
推荐答案
您调用的第二个参数应该是你传递的格式。日期时间被创建后,您可以指定输出格式为:
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");
这篇关于如何字符串转换为C#日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!