John Flaherty
John Flaherty

Reputation: 31

Passing DateTime in api url in c#

I have an api url in the following format;

https://MyAPI.com/stuff/pending_since/{{DATE-TIME}}

I've tried;

var myDate = new DateTime(2020, 1, 1);
var stringTask = client.GetStringAsync("https://MyAPI.com/stuff/pending_since/{{myDate}}");
var json = await stringTask;
Console.WriteLine(json);

That returns an error. How do I pass the date in the url? Thanks, John

Upvotes: 1

Views: 2110

Answers (1)

haldo
haldo

Reputation: 16691

You need to use a format which doesn't contain slashes, otherwise it'll mess up the Url, and use InvariantCulture when formatting the date.

string dateStr = myDate.ToString("s", CultureInfo.InvariantCulture);
var stringTask = client.GetStringAsync($"https://MyAPI.com/stuff/pending_since/{dateStr}");

where the format specifier s is known as the Sortable date/time pattern.

The date will be formatted as: yyyy-MM-ddTHH:mm:ss which should be compatible with URLs.

Also, as Hans mentioned, you will probably need to use an interpolated string: $"https://MyAPI.com/stuff/pending_since/{dateStr}" in GetStringAsync (prepended with $ and only one set of {} braces.

Upvotes: 2

Related Questions