考虑到:

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"

其他回答

如果你在SharePoint 2010或更高版本下开发,你可以使用

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
...
string strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)

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

我将使用XmlConvert:

XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);

它会自动保存时区。

像2018-06-22T13:04:16这样的格式可以在API的URI中传递:

public static string FormatDateTime(DateTime dateTime)
{
    return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
}

转换DateTime。UtcNow转换为yyyy-MM-ddTHH:mm:ssZ的字符串表示形式,您可以使用DateTime结构的ToString()方法与自定义格式化字符串。在使用带有DateTime的自定义格式字符串时,重要的是要记住需要使用单引号转义分隔符。

下面将返回你想要的字符串表示:

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)