問題描述
給定一個 DateTime 對象,如何獲取字符串格式的 ISO 8601 日期? (Given a DateTime object, how do I get an ISO 8601 date in string format?)
給定:
DateTime.UtcNow
如何在 符合 ISO 8601 的格式?
請注意,ISO 8601 定義了許多類似的格式。我要找的具體格式是:
yyyy‑MM‑ddTHH:mm:ssZ
參考解法
方法 1:
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", CultureInfo.InvariantCulture);
Using custom date‑time formatting, this gives you a date similar to
2008‑09‑22T13:57:31.2311892‑04:00.
Another way is:
DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
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", CultureInfo.InvariantCulture)
方法 2:
DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture)
should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.
EDIT: To get the additional Z
at the end as the OP requires, use "o"
instead of "s"
.
方法 3:
DateTime.UtcNow.ToString("s")
Returns something like 2008‑04‑10T06:30:00
UtcNow
obviously returns a UTC time so there is no harm in:
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
方法 4:
Use:
private void TimeFormats()
{
DateTime localTime = DateTime.Now;
DateTime utcTime = DateTime.UtcNow;
DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));
//UTC
string strUtcTime_o = utcTime.ToString("o");
string strUtcTime_s = utcTime.ToString("s");
string strUtcTime_custom = utcTime.ToString("yyyy‑MM‑ddTHH:mm:ssK");
//Local
string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy‑MM‑ddTHH:mm:ssK");
//Output
Response.Write("<br/>UTC<br/>");
Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");
Response.Write("<br/>Local Time<br/>");
Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");
}
OUTPUT
UTC
strUtcTime_o: 2012‑09‑17T22:02:51.4021600Z
strUtcTime_s: 2012‑09‑17T22:02:51
strUtcTime_custom: 2012‑09‑17T22:02:51Z
Local Time
strLocalTimeAndOffset_o: 2012‑09‑17T15:02:51.4021600‑07:00
strLocalTimeAndOffset_s: 2012‑09‑17T15:02:51
strLocalTimeAndOffset_custom: 2012‑09‑17T22:02:51Z
Sources:
方法 5:
System.DateTime.UtcNow.ToString("o")
=>
val it : string = "2013‑10‑13T13:03:50.2950037Z"
(by Iain、Wayne、Simon Wilson、Iain、Don、Henrik)