如何解析并生成ISO 8601格式的DateTime对象 [英] How to parse and generate DateTime objects in ISO 8601 format

查看:370
本文介绍了如何解析并生成ISO 8601格式的DateTime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个SOAP Web服务以下列格式发送我的datetime对象

There is this SOAP web service that sends me datetime objects in the following format

2016-03-29T12:20:35.093-05:00

这是2016年3月29日的时间:12:20: 35.093(GMT-5)。

That is day 29 of March of year 2016. Hour: 12:20:35.093 (GMT-5).

我想要创建一个 DateTime 对象,像这样: / p>

I want to be able to create a DateTime object, like this:

DateTime.Now

并以上述格式获取字符串表示形式,并且还可以使用反向操作,从上面给出的字符串创建一个DateTime。

and get the string representation in the format described above and also the inverse operation, create a DateTime from a string like the one given above.

为了创建日期,我尝试过以下操作:

I've tried the following in order to create the date:

new DateTime(2016, 3, 29, 12, 20, 35, 093, DateTimeKind.Utc)

但是,我看不到如何指定GMT-5那里...

However, I can't not see how to specifie GMT-5 there...

我不知道如何将DateTime转换为指定的字符串格式。

I don't know how to convert a DateTime to the specified string format, either.

使用Nate的代码我正在执行以下操作:

var d = new DateTimeOffset(2016, 3, 29, 12, 20, 35, 93, TimeSpan.FromHours(-3));

FormatIso8601(d)

但是这个调用正在返回:2016- 03-29T15:20:35Z而不是:

However this call is returning: "2016-03-29T15:20:35Z" instead of :

"2016-03-29T12:20:35.093-03:00"

这是我实际需要的。

我认为这样做:

        d.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz")


推荐答案

您所描述的格式是 ISO 8601

由于您正在使用inclulde一个时区组件,我强烈建议使用 DateTimeOffset 而不是 DateTime 。它使事情变得更加容易!

Since you're working with timestamps that inclulde a time zone component, I'd strongly recommend using DateTimeOffset instead of DateTime. It makes things so much easier!

为给定日期,时间和时区偏移创建一个 DateTimeOffset ,请使用以下语法:

To create a DateTimeOffset for a given date, time, and time zone offset, use this syntax:

var date = new DateTimeOffset(2016, 3, 29, 12, 20, 35, 93, TimeSpan.FromHours(-5));
// March 29, 2016 at 12:20:35.93 GMT-5

将格式化 DateTimeOffset 作为ISO 8601:

This code will format a DateTimeOffset as ISO 8601:

public static string FormatIso8601(DateTimeOffset dto)
{
    string format = dto.Offset == TimeSpan.Zero
        ? "yyyy-MM-ddTHH:mm:ss.fffZ"
        : "yyyy-MM-ddTHH:mm:ss.fffzzz";

    return dto.ToString(format, CultureInfo.InvariantCulture);
}

而且,将一个字符串解析回 DateTimeOffset

And, to parse a string back to a DateTimeOffset:

public static DateTimeOffset ParseIso8601(string iso8601String)
{
    return DateTimeOffset.ParseExact(
        iso8601String,
        new string[] { "yyyy-MM-dd'T'HH:mm:ss.FFFK" },
        CultureInfo.InvariantCulture,
        DateTimeStyles.None);
}

如果你必须回到 DateTime 你可以从 DateTimeOffset 获得这个。 UtcDateTime 属性。

If you must get back to a DateTime you can get this from the DateTimeOffset.UtcDateTime property.

这篇关于如何解析并生成ISO 8601格式的DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆