How to convert this date 2017-07-09T17:50:21.000-0500 | C#

时间:2017-06-09 12:46:29

标签: c# datetime

when i run the below code, string dt = "2017-07-09T17:50:21.000-0500"; DateTime date = Convert.ToDateTime(dt);

it gives me output as

7/10/2017 4:20:21 AM

where as i want my output to be

2017-07-09 17:50


update

the code @alexander-petrov gave worked string dt = "2017-07-09T17:50:21.000-0500"; string date = DateTimeOffset.Parse(dt).DateTime.ToString("yyyy-MM-dd HH:mm");

gives output

2017-07-09 17:50

but on inserting the same to database it is adding +5 hrs to the time and inserting as

2017-07-09 22:50

4 个答案:

答案 0 :(得分:1)

这是DateTime格式DateTimeKind.Local指定的System.Globalization.DateTimeStyles.RoundtripKind类型。
您需要确定您的程序是否需要了解时区。

您可以尝试解析它,同时向System.Globalization.DateTimeStyles.AdjustToUniversal方法提供Parse.gradle参数。

答案 1 :(得分:0)

I couldn't get your date to work, as I think there is a colon missing in the last part. Adding that colon back allows me to convert the XSD date time into a SQL DATETIME using this script:

DECLARE @stringDate VARCHAR(30);
SELECT @stringDate = '2017-07-09T17:50:21.000-05:00';
DECLARE @xmlDate XML;
SELECT @xmlDate = CAST('' AS XML);
SELECT @xmlDate.value('xs:dateTime(sql:variable("@stringDate"))', 'datetime');

Results:

2017-07-09 22:50:21.000

答案 2 :(得分:0)

尝试:

string date = "2017-07-09T17:50:21.000-0500";
DateTime d = DateTime.ParseExact(date, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz", null);

答案 3 :(得分:0)

如果您想要考虑偏移量,请使用DateTimeOffset类型。

string dt = "2017-07-09T17:50:21.000-0500";

DateTimeOffset date = DateTimeOffset.Parse(dt);

// format on my machine
// 09.07.2017 17:50:21 - 05:00
Console.WriteLine(date);

// without offset
// 09.07.2017 17:50:21
Console.WriteLine(date.DateTime);