考虑到:
DateTime.UtcNow
我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?
请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:
yyyy-MM-ddTHH:mm:ssZ
考虑到:
DateTime.UtcNow
我如何获得一个字符串,它表示在ISO 8601兼容的格式相同的值?
请注意,ISO 8601定义了许多类似的格式。我想要的具体格式是:
yyyy-MM-ddTHH:mm:ssZ
当前回答
System.DateTime.UtcNow.ToString("o")
=>
val it : string = "2013-10-13T13:03:50.2950037Z"
其他回答
The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
-来自MSDN
如果你在SharePoint 2010或更高版本下开发,你可以使用
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
...
string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)
使用Newtonsoft。Json,你可以这样做
JsonConvert.SerializeObject(DateTime.UtcNow)
例如:https://dotnetfiddle.net/O2xFSl
DateTime.UtcNow.ToString("s")
返回类似2008-04-10T06:30:00的内容
UtcNow显然返回UTC时间,所以在以下情况下没有伤害:
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
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/>");
}
输出
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
来源:
标准日期和时间格式字符串(MSDN) 自定义日期和时间格式字符串(MSDN)