I have a custom validation attribute in my ASP.NET Web API application that checks if the date is in the future or not (dates in the future are not allowed). Here's the code:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var date = (DateTime)value;
if (date != null)
{
if(date.Date > DateTime.UtcNow.Date)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
}
return ValidationResult.Success;
}
I can't figure out how to make the comparison so it works for all time-zones. Using DateTime.UtcNow
is not the solution, because if the client and the server are in the same timezone, in the hours close to midnight, the date will be the day after. And, of course DateTime.Now
wouldn't work for other time-zones. So, what's the solution?
Update:
In my WebApiConfig.cs
file, I have this code to set the DateTimeZoneHandling
to Utc
:
jsonFormatter.SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
This will format the date in the JSON response like this: "2018-03-02T00:00:00Z".
And, all the DateTime values coming from the client will have their Kind
property set to Utc
. Then, I can compare the date with UtcNow
, but now the problem is the date "2018-03-02T00:00:00Z" is displayed as March 1, 2018 in my browser, because it is converted to local time (UTC -5).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…