DateTimeOffset TryParse not accepting valid datetime – C# OWIN implementation

I’m using C# OWIN framework for authentication and I have the TokenEndpoint override method which converts IssuedDate & ExpiresDate in the proper format, so I have used DateTimeOffset.TryParse method to check and return datetime, so now the issue that I ‘m facing is really strange, one of the service works properly that returns true for the method DateTimeOffset.TryParse while the other service returns false even though both are passing the same date format. Earlier I used DateTimeOffset.Parse and it failed with the reason ‘string was not recognized as a valid datetime.’ so I changed to DateTimeOffset.TryParse to handle error but I ‘m still not able to find the root cause.

 public override async Task TokenEndpoint(OAuthTokenEndpointContext context)
            foreach (System.Collections.Generic.KeyValuePair<string, string> property in context.Properties.Dictionary)
                DateTimeOffset result;
                if ((property.Key.Equals(".issued") || property.Key.Equals(".expires")) && DateTimeOffset.TryParse(property.Value, out result))
                    context.AdditionalResponseParameters.Add(property.Key, result.UtcDateTime.ToString("yyyy/MM/dd HH:mm:ss"));
                    context.AdditionalResponseParameters.Add(property.Key, property.Value);

Both the services passes date in the below format. Sun, 07 Mar 2021 11:31:14 GMT Sun, 07 Mar 2021 11:32:44 GMT

Please check the snapshotenter image description here


Maybe the two threads have different Cultures?

Try to specify the date time format:

var result = DateTimeOffset.TryParse(
                "Sun, 07 Mar 2021 11:31:14 GMT", 
                out var date);

Or use DateTimeOffset.TryParseExact.

Leave a Reply

Your email address will not be published. Required fields are marked *