In asp.net Date.Now
generates a complete date string:
e.g "2018-01-17T11:12:42.0544453+00:00"
I am unable to validate this date string with the following formats. Can anyone suggest a suitable validation format?
Dim formats() As String = {
"yyyy-MM-dd",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-mm-ddThh:mm:ss.ffffff",
"yyyy-mm-ddThh:mm:ss.fffffffZ",
"yyyy-mm-ddThh:mm:ss.nnnnnnn",
"yyyy-mm-ddThh:mm:ss.nnnnnnnZ",
"yyyy-mm-ddThh:mm:ss.nnnnnnn+|-hh:mm"
}
If Date.TryParseExact("2018-01-17T11:12:42.0544453+00:00", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, dt) Then
//Success
End If
I want to ensure the date is a valid ISO 8601 date format. This can be true even when time/fractions/timeszones are omitted.
You can use the "O"(Round-trip) format specifier
Dim time = "2018-01-17T11:12:42.0544453+00:00"
Dim validDate = Date.TryParseExact(time, "O", CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For
DateTime
values, this format specifier is designed to preserve date and time values along with theDateTime.Kind
property in text. ...
Side-note: for me Date.Now.ToString
doesn't return a string in this format. Maybe you have used:
Dim time = Date.UtcNow.ToString("o", System.Globalization.CultureInfo.InvariantCulture)