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
1 Answer 1
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.
2 Comments
$"https://MyAPI.com/stuff/pending_since/{dateStr}"
(note the leading $
and the single { }
)
myDate
rather than just letting .NET use whatever the current thread's culture is to determine the format. As you can see, different cultures will have different formats. The default culture an applications starts under depends on the OS settings.https://MyAPI.com/stuff/pending_since/{{myDate}}
. You're not using the value of the variable at all. I don't know whether that's because you made a mistake when creating the code for the question, or whether that's actually in the broken code you're running. This is where a minimal reproducible example would really help...