在C#中转换DateTime格式 [英] Convert DateTime Format in C#
问题描述
如何从webservice转换此datetime格式。 datetime值为:timestamp:2014-04-18T14:45:00 + 02:00
我不会将其转换为:dd.mm.YYYY hh.mm.ss
您需要使用yyyy-MM-dd'T'HH:mm:ssK
格式与 InvariantCulture
使用 DateTime.ParseExact
方法,如;
string s =2014-04-18T14:45:00 + 02:00;
var date = DateTime.ParseExact(s,yyyy-MM-dd'T'HH:mm:ssK,
CultureInfo.InvariantCulture);
看看 K
自定义格式说明符
然后,您可以使用 DateTime 的字符串表示/en-us/library/k494fzbf%28v=vs.110%29.aspxrel =nofollow> DateTime.ToString()
方法。 DateTime
没有固有的格式,它只有一个值。您可以获取格式的字符串表示。
date.ToString(dd.MM.yyyy HH.mm.ss,CultureInfo不变文化);
//18.04.2014 03.45.00
这里一个 演示
。
记住, mm
是分钟, MM
几个月。而 hh
是用于的小时时钟,这是 01
到 12
。但是, HH
是 c> c 00
23 。
这就是为什么你无法解析 14
与 hh
说明符。我假设你的真实代表格式是 dd.MM.yyyy HH.mm.ss
编辑:在您的评论之后,您可以使用MM / dd / yyyy HH:mm:ss
格式如:
string s =04/18/2014 14:45:00;
var date = DateTime.ParseExact(s,MM / dd / yyyy HH:mm:ss,
CultureInfo.InvariantCulture);
Console.WriteLine(date); // 18/04/2014 14:45:00
How can I convert this datetime format from a webservice. The datetime value is: "timestamp": "2014-04-18T14:45:00+02:00" I wan't to convert it to: dd.mm.YYYY hh.mm.ss
You need to use "yyyy-MM-dd'T'HH:mm:ssK"
format with InvariantCulture
using DateTime.ParseExact
method like;
string s = "2014-04-18T14:45:00+02:00";
var date = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK",
CultureInfo.InvariantCulture);
Take a look at The "K"
Custom Format Specifier
Then you can get string representation of your DateTime
with DateTime.ToString()
method. DateTime
has no inherent format, it has just a value. You can get string representation for formatting.
date.ToString("dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture);
//18.04.2014 03.45.00
Here a demonstration
.
Remember, mm
is for minutes, MM
for months. And hh
is for 12-hour clock which is 01
to 12
. But HH
is 24-hour clock which is 00
to 23
.
That's why you can't parse 14
with hh
specifier. I assume your real representation format is dd.MM.yyyy HH.mm.ss
EDIT: After your comment, you can use "MM/dd/yyyy HH:mm:ss"
format like;
string s = "04/18/2014 14:45:00";
var date = DateTime.ParseExact(s, "MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Console.WriteLine(date); // 18/04/2014 14:45:00
这篇关于在C#中转换DateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!