Recipe 7.22. Dates and Times in ISO 8601 Formats


You want to format a date and time into a string using the ISO 8601 standard, with a "T" separating the date and time parts and an optional "Z" at the end if Coordinated Universal Time is used.


Sample code folder: Chapter 07\ISO8601

Use the single-character "s" string-format parameter and concatenate a "Z" if Coordinated Universal Time is used.


String formatting in .NET has much of the ISO 8601 standard built in. The "s" string-format parameter creates a date and time string of the form "yyyy-mm-ddThh:mm:ss," and the "u" format parameter creates the same string minus the "T" that separates the date and time parts and with a "Z" at the tail end to signify Coordinated Universal Time. The standard is actually fairly relaxed about the "T" separator requirement, so these two string-formatting parameters cover most bases. The first two lines of output in Figure 7-23 show the strings created using these formatting parameters.

Figure 7-23. Date and time strings that closely conform to the ISO 8601 standard

One scenario not covered is when you want to include both the "T" separator character and the "Z" at the tail end. As shown previously, the "s" and "u" formatting parameters give you one or the other but not both. The other scenario not covered is when you want to drop both the "T" and the "Z" from the string. Fortunately, it's easy to add this functionality.

The following code was used to create the output shown in Figure 7-23:

 Dim rightNow As Date = Now.ToUniversalTime Dim format1 As String = rightNow.ToString("s") Dim format2 As String = rightNow.ToString("u") Dim format3 As String = rightNow.ToString("s") & "Z" Dim format4 As String = rightNow.ToString( _    "u").Substring(0, 19) MsgBox(String.Format( _    "s: {1}{0}u: {2}{0}T&Z: {3}{0}Neither: {4}", _    vbNewLine, format1, format2, format3, format4)) 

To add both the "T" and the "Z" to the formatted string, use the "s" format and concatenate a "Z" to the tail of the result. format3 in the code and the third line of the output demonstrate this technique.

To eliminate both the "T" and the "Z" from the ISO-formatted string, use the "u" format parameter to create a 20-character string; then use Substring() to drop the "Z" from the tail end.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400 © 2008-2017.
If you may any questions please contact us: