How to write a date in type of ISO 8601

-1

I'm doing a communication program with apis online and I'm using a header of type DateTime and I needed that date to be in type ISO 8601 how can I do that?

I'm using this to create the header:

var tempo = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
var httpWebRequest = (HttpWebRequest)WebRequest.Create("teste");
httpWebRequest.Headers.Add("Date"+ tempo);

The output is this:

  

Date2017-09-08T15: 25: 53Z

I wanted it to be this:

  

Date: 2017-09-08T15: 25: 53Z

    
asked by anonymous 08.09.2017 / 17:12

3 answers

3
DateTime.UtcNow.ToString("o");

or

DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");

Font .

Documentation .

This is how a text is represented in the specified format. A DateTime is not formatted, it's a date is ready, only texts are formatted. For the question, including the edition, what you want is a text with the representation and not the date itself which is a quantitative number.

Actually the question is chameleon, what you really want is not the date in ISO format but rather build the text correctly, like this:

httpWebRequest.Headers.Add($"Date: {DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")}");

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
08.09.2017 / 17:16
2

Option 1:

DateTime.UtcNow.ToString("o");

Option 2:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");

Option 3 (with the specified format specified):

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); 

Reference

    
08.09.2017 / 17:16
0
var tempo = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
var httpWebRequest = (HttpWebRequest)WebRequest.Create("teste");
httpWebRequest.Headers.Add("Date: "+ tempo);
    
08.09.2017 / 18:46