如何使用c#将var转换为日期时间? [英] How to convert var into date time using c#?
问题描述
var t =(从列表2中的li选择li).Max();
上面的代码给了我一个输出 2014-06-03 10:07 :31 AM
现在我想将其转换为'03_06_2014_10_07_31'
所以我首先尝试将格式更改为 'MM / dd / yyyy HH:mm:ss'
通过使用以下,以便我可以使用一些拆分等等,使它'03_06_2014_10_07_31'
DateTime dfg = DateTime.ParseExact(t,MM / dd / yyyy HH:mm:ss,
CultureInfo.InvariantCulture);
但它显示
字符串未被识别为有效的DateTime。
我想更改 2014-06- 03 10:07:31 AM
into 03_06_2014_10_07_31
A DateTime
没有隐式格式,它只是一个 DateTime
的值。您可以将其格式化为字符串
值。
使用指定的格式和文化特定的
将日期和时间的指定字符串表示形式转换为其
DateTime等价物格式信息。 字符串表示形式的格式必须与指定格式的
完全匹配。
在您的情况下他们不是。
使用 yyyy-dd-MM HH:mm:ss tt
p>
这里是 LINQPad ;
string s =2014-06-03 10:07:31 AM;
DateTime dfg = DateTime.ParseExact(s,yyyy-dd-MM HH:mm:ss tt,
CultureInfo.InvariantCulture);
dfg.Dump();
这里有一个 演示
。
之后,您可以使用 DateTime %29.aspxrel =nofollow> .ToString()
方法,如;
dfg.ToString(MM / dd / yyyy HH:mm:ss,CultureInfo.InvariantCulture);
打印 03/06/2014 10:07:31
或
dfg.ToString(MM_dd_yyyy_HH_mm_ss ,CultureInfo.InvariantCulture);
打印 03_06_2014_10_07_31
I wan to convert a var into data and time how to do that
var t = (from li in list2 select li).Max();
the above code give me a output 2014-06-03 10:07:31 AM
now I want to convert this into '03_06_2014_10_07_31'
so first I tried to change the format to 'MM/dd/yyyy HH:mm:ss'
by using the below so that I can use some split and so on and make it '03_06_2014_10_07_31'
DateTime dfg = DateTime.ParseExact(t, "MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
But it showing
String was not recognized as a valid DateTime.
I want to change 2014-06-03 10:07:31 AM
into 03_06_2014_10_07_31
A DateTime
has no implicit format, it is just a DateTime
value. You can format it as a string
value.
From 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.
In your case, they are not.
Use yyyy-dd-MM HH:mm:ss tt
format instead.
Here an example in LINQPad;
string s = "2014-06-03 10:07:31 AM";
DateTime dfg = DateTime.ParseExact(s, "yyyy-dd-MM HH:mm:ss tt",
CultureInfo.InvariantCulture);
dfg.Dump();
Here a demonstration
.
After that, you can format your DateTime
with .ToString()
method like;
dfg.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
prints 03/06/2014 10:07:31
or
dfg.ToString("MM_dd_yyyy_HH_mm_ss", CultureInfo.InvariantCulture);
prints 03_06_2014_10_07_31
这篇关于如何使用c#将var转换为日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!