1

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

asked Jan 28, 2022 at 15:11
4
  • You'll probably want to specify a format for 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. Commented Jan 28, 2022 at 15:19
  • 1
    Also: what is the format the API requires specifically? Commented Jan 28, 2022 at 15:21
  • "That returns an error" - when you ask a question about an error, always give precise details about the error. What kind of error is it? What's the exact text of the error message? Commented Jan 28, 2022 at 16:25
  • Note that the URL you're hitting is literally 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... Commented Jan 28, 2022 at 16:26

1 Answer 1

2

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.

answered Jan 28, 2022 at 15:18
Sign up to request clarification or add additional context in comments.

2 Comments

@JohnFlaherty Could you add the exact error message to the question please?
You may need to use $"https://MyAPI.com/stuff/pending_since/{dateStr}" (note the leading $ and the single { })

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.