Search code examples
c#datetimetryparse

How to write date format which will cover all precisions or length of milliseconds of DateTime.UtcNow?


Sometimes DateTime.UtcNow returns me different length of milliseconds:

2025-02-27T06:01:59.7581509Z
2025-02-27T06:21:48.190694Z

The difference is between length of milliseconds. So 7581509 has length 7 and 190694 has length 6. I need to use TryParseExact and so I have written the following date formats "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"

So this TryParseExact works perfectly and return true:

if (DateTime.TryParseExact(
        "2025-02-27T06:21:48.190694Z",
        "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'",
        CultureInfo.InvariantCulture,
        DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
        out DateTime utcParsedValue))
{
    var test = utcParsedValue;
}

But this TryParseExact return false because 7581509 has length 7.

if (DateTime.TryParseExact(
        "2025-02-27T06:01:59.7581509Z",
        "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'",
        CultureInfo.InvariantCulture,
        DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
        out DateTime utcParsedValue))
{
    var test = utcParsedValue;
}

Yeah, I know that it will work, if I add additional f into date format yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'. But this code will fail if the length of milliseconds would 8. How to write date format which will cover all precisions or length milliseonds?


Solution

  • You FFFFFFF instead of fffffff (see Custom date and time format strings docs).

    Updated code:

    if (DateTime.TryParseExact(
            "2025-02-27T06:01:59.7581509Z",
            "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'",
            CultureInfo.InvariantCulture,
            DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
            out DateTime utcParsedValue))
    {
        var test = utcParsedValue;
    }
    

    But do you have a need to be so exact with the format string? Would something like this work better for your use case?:

    if(DateTime.TryParse(
        "2025-02-27T06:01:59.7581509Z",
        CultureInfo.InvariantCulture,
        DateTimeStyles.AdjustToUniversal,
        out DateTime utcParsedValue))
    {
        var test = utcParsedValue;
    }
    

    If you're sure that all of the dates you'll receive won't have an offset (i.e. Z or +0000) then DateTime.TryParse(...) by itself should work.