Close

DateTime fiels in API Models

When building a REST service in .Net (ASP.Net Web Application, API template), you obviously build controllers and models. In this example I created a ProductService with mutationDateTime being one of the properties of the Product model class. The question is: how do we define mutationDateTime? Because json doesn’t know datetime fields, I thought you were forced to use a string in combination with a regular expression, like below:

[RegularExpression(@”^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\dZ)$”)]
public string mutationDateTime { get; set; }

This solution works, but the regular expression is a bit complex. As an alternative I replaced the regular expression with the following annotation.

[DataType(DataType.DateTime)]
public string mutationDateTime { get; set; }

When passing an invalid date, no validation exception was raised, so apparently this construct doesn’t actually force the string to be a valid datetime. As a last attempt. I added a statement using System. Then I replaced the string data type by a DateTime.

using System;
public DateTime mutationDateTime { get; set; }

Now, when testing again, I actually received a validation exception. Then I tried to pass a valid date and a valid datetime as a string. Both actions worked. When being very critical, one could argue that I can’t force a client to pass a date instead of a datetime, but I take that for granted given the reduced complexity.

“discountDateStart”: “2019-05-29T08:47:53.827Z”,
“discountDateEnd”: “2012-04-23”,