Passing DateTimeOffset as WebAPI query string

前端 未结 8 598
感动是毒
感动是毒 2020-12-11 15:49

I\'ve got a WebAPI action that looks like so:

[Route(\"api/values/{id}\")]
public async Task Delete(string id, DateTimeOffset date         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 16:23

    Answer

    To send a DateTimeOffset to your API, format it like this after converting it to UTC:

    2017-04-17T05:04:18.070Z

    The complete API URL will look like this:

    http://localhost:1234/api/values/1?date=2017-04-17T05:45:18.070Z

    It’s important to first convert the DateTimeOffset to UTC, because, as @OffHeGoes points out in the comments, the Z at the end of the string indicates Zulu Time (more commonly known as UTC).

    Code

    You can use .ToUniversalTime().ToString(yyyy-MM-ddTHH:mm:ss.fffZ) to parse the DateTimeOffset.

    To ensure your DateTimeOffset is formatted using the correct timezone always use .ToUniversalTime() to first convert the DateTimeOffset value to UTC, because the Z at the end of the string indicates UTC, aka "Zulu Time".

    DateTimeOffset currentTime = DateTimeOffset.UtcNow;
    string dateTimeOffsetAsAPIParameter = currentDateTimeOffset.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
    string apiUrl = string.Format("http://localhost:1234/api/values/1?date={0}", dateTimeOffsetAsAPIParameter);
    

提交回复
热议问题