user123
user123

Reputation: 91

How to send datetime from mvc to web api as a parameter?

Now when i'm sending it from mvc controller to web api like '01-05-2020 00:00:00' web api gets it as '05-01-2020 00:00:00' and if i send '21-04-2020 00:00:00' it gives Error 400: BadRequest.

I'm getting parameters in web api as

IHttpActionResult Applications(DateTime fromDate,DateTime toDate)

Mvc Controller

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44329/api/Values");
var postTask = client.GetAsync("/api/Values/Applications?fromDate=" + FromDate + "&toDate=" + ToDate );

Upvotes: 3

Views: 2027

Answers (1)

Markus
Markus

Reputation: 22436

When sending dates to an API, it is recommended to use a format that is independent of the culture. Widely used is the ISO 8601 format.

You can convert your dates to ISO 8601 by calling ToString("O"):

var postTask = client.GetAsync("/api/Values/Applications?fromDate=" + FromDate. ToString("O") + "&toDate=" + ToDate.ToString("O"));

For details on the Format, see this link: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#the-round-trip-o-o-format-specifier

Please also note that the timezone is another parameter to respect, so transmitting and also expecting the dates as UTC is a good practice to avoid timezone related issues.

Upvotes: 6

Related Questions