给定一个 DateTime 对象,如何以字符串格式获取 ISO 8601 日期? [英] Given a DateTime object, how do I get an ISO 8601 date in string format?

查看:26
本文介绍了给定一个 DateTime 对象,如何以字符串格式获取 ISO 8601 日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

DateTime.UtcNow

我如何获得一个以ISO 8601兼容格式表示相同值的字符串?

How do I get a string which represents the same value in an ISO 8601-compliant format?

请注意,ISO 8601 定义了许多类似的格式.我要找的具体格式是:

Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:

yyyy-MM-ddTHH:mm:ssZ

推荐答案

读者须知:一些评论者指出了这个答案中的一些问题(特别是与第一个建议有关).有关详细信息,请参阅评论部分.

Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.

DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");

使用自定义日期时间格式,这会给你一个类似于
的日期2008-09-22T13:57:31.2311892-04:00.

Using custom date-time formatting, this gives you a date similar to
2008-09-22T13:57:31.2311892-04:00.

另一种方式是:

DateTime.UtcNow.ToString("o");

使用标准 往返"样式 (ISO 8601) 给你
2008-09-22T14:01:54.9571247Z.

which uses the standard "round-trip" style (ISO 8601) to give you
2008-09-22T14:01:54.9571247Z.

要获取指定的格式,可以使用:

To get the specified format, you can use:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")

这篇关于给定一个 DateTime 对象,如何以字符串格式获取 ISO 8601 日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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