Mac
Mac

Reputation: 25

date issue with Rest API

I am using Jira Rest API. The problem is when I make POST request then I get error:

The remote server returned an error: (500) Internal Server Error

After investigating, I came to understand that the problem is with a date format. When I use the exact date shown below then my request works.

2016-11-09T05:28:58.211+0000

Can anyone help me determine what exactly is this format -- it looks similar to ISO 8601. I tried the code below but it does not work:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss.fffzfff")
Output: 2016-11-29T01:37:34.453+2453

Upvotes: 0

Views: 1991

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241920

You are just not formatting correctly.

DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss.fffK")
// "2016-11-28T23:50:06.657+00:00"

Note hours need to be HH, not hh, you shouldn't use fff twice, and you should use K with DateTime, not z.

Ideally, ISO8601 extended format should have a colon in the offset, +00:00 instead of +0000. It is still valid ISO8601 without the colon, but you probably shouldn't omit it unless you're aiming for the ISO8601 compact format, which would also remove all dashes and colons from the entire string.

If you really can't handle the colon in the offset, and want the rest to use the extended format, you'll have to remove the one colon manually.

var s = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss.fffK");
s = s.Substring(0, 26) + s.Substring(27,2);
// "2016-11-28T23:50:06.657+0000"

As for why you should use K instead of something like zzz - this comes down to the fact that DateTime has a Kind property, and DateTimeOffset has an offset instead. More on this here and here.

Also, keep in mind that you probably don't want to use DateTime.Now in a REST API. That API is probably running on a server, and the local time zone of the server should be mostly irrelavent to your application, your API, and it's external consumers. Instead, you probably want to just use DateTime.UtcNow, and your output will give a Z instead of +00:00 when you use the K specifier. This is preferred anyway.

Upvotes: 4

Related Questions