Given a DateTime object, how do I get an ISO 8601 date in string format?

后端 未结 18 2525
暖寄归人
暖寄归人 2020-11-22 02:15

Given:

DateTime.UtcNow

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

Note that ISO 8601 de

18条回答
  •  庸人自扰
    2020-11-22 02:22

    You can get the "Z" (ISO 8601 UTC) with the next code:

    Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)
    Dim res as String = tmpDate.toString("o") '2009-06-15T13:45:30.0000000Z
    


    Here is why:

    The ISO 8601 have some different formats:

    DateTimeKind.Local

    2009-06-15T13:45:30.0000000-07:00
    

    DateTimeKind.Utc

    2009-06-15T13:45:30.0000000Z
    

    DateTimeKind.Unspecified

    2009-06-15T13:45:30.0000000
    


    .NET provides us with an enum with those options:

    '2009-06-15T13:45:30.0000000-07:00
    Dim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString("o")
    
    '2009-06-15T13:45:30.0000000Z
    Dim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString("o")
    
    '2009-06-15T13:45:30.0000000
    Dim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString("o")
    

    Note: If you apply the Visual Studio 2008 "watch utility" to the toString("o") part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.

    Source: Standard Date and Time Format Strings (MSDN)

提交回复
热议问题