Convert DateTime Format in Web API - c#

We exposed a Web API with OData protocol. The issue we had is that customer sends requests with a defined DateTime format. Something like this: 2020-10-10T10:21+02:00. How we could convert this date to this format 2020-10-10T12:21? Is it possible to be done in WebAPIConfig? or it should be done in controllers part? How it could be reached?

The easiest way is to use the method .ToString() with the correct parameter on the Datetime object in the controller to get the format that u want to use.
Example of datetime formats .ToString()

Related

AspNet Core - Specify the DateTime Format

I am consuming a third party API which expects an HTTP header value as below (using the format below).
Date: 2017-10-15T14:25:21Z
When I try to add the header as below, I am getting invalid date time format error (when the client inject the header during runtime)
client.DefaultRequestHeaders.Add("Date", "2017-10-15T14:25:21Z");
So I change the code above to as below
client.DefaultRequestHeaders.Date = DateTime.UtcNow;
However, the API throws back an exception "Hmac timestamp 2019-01-02 is not a valid ISO8601 dateTime"
How do I pass the expected date time format in the HTTP request header?
EDIT
-
I know how to get a date string in a specified format. What I am asking here is how do I pass a UTC date object to HTTP header as below with a specific format. I also realise that datetime object cant have a format in it.
**client.DefaultRequestHeaders.Date = DateTime.UtcNow**
Do that like this
DateTime dt=Convert.ToDateTime("2019-01-02");
string yourdate = dt.ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(yourdate);
Working example

C# DateTimeInvalidLocalFormat - How to set timezone to UTC

I'm working in a EasyPost integration making a class library to make the use of their API simpler and I'm getting this error:
Managed Debugging Assistant 'DateTimeInvalidLocalFormat' has detected a problem in 'C:\Projects\TestClient.vshost.exe'.
Additional information: A UTC DateTime is being converted to text in a format that is only correct for local times. This can happen when calling DateTime.ToString using the 'z' format specifier, which will include a local time zone offset in the output. In that case, either use the 'Z' format specifier, which designates a UTC time, or use the 'o' format string, which is the recommended way to persist a DateTime in text. This can also occur when passing a DateTime to be serialized by XmlConvert or DataSet. If using XmlConvert.ToString, pass in XmlDateTimeSerializationMode.RoundtripKind to serialize correctly. If using DataSet, set the DateTimeMode on the DataColumn object to DataSetDateTime.Utc.
I get this error when I call the Create method in the EasyPost Shipment object. Code below:
Shipment shipment = new Shipment() {
to_address = toAddress,
from_address = fromAddress,
parcel = parcel
};
shipment.Create();
This create function probably makes a call to their REST API and is trying to convert a json response into one of their models.
To solve the error I'm trying to set the UTC as the default of my library so whenever I use DateTime.ToString() I use the DateTime.ToString("o"). I don't know if this would actually solve the problem, but I don't know how to force it (use UTC as the library default). I have tried the piece of code below, but it doesn't work
CultureInfo newCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = newCulture;
Can you help me?
I'm one of the developers on the EasyPost client libraries.
As far as I can find in some basic research, there's no (easy) way to set a default time zone for a C# application. Most of the blog posts and other SO answers I found suggest using utility functions to convert a UTC datetime object to a local datetime object when trying to display it to a string.
EasyPost's API returns all datetimes in UTC time + timezone information (ex. 2022-10-24T12:37:24-06:00), which is accounted for when the JSON is deserialized into a DateTime object in the C# client library.

JSON parse DateTime

From the server I get this string
[{\"id\":\"9b77ff1e-350e-44d8-8860-15e80f4d8a22\",\"code\":\"C\",\"name\":\"0%\",\"validFrom\":\"2013-07-01T00:00:00Z\",\"validTill\":null,\"active\":1,\"vatProc\":0.0,\"createdAt\":\"2015-02-01T13:04:17.733Z\",\"updatedAt\":\"2015-02-01T13:04:17.733Z\"}]
On the client side I then convert it to a json object using JSON.parse which produces the result:
[
{
active:1
code:"C"
createdAt:"2015-02-01T13:04:17.733Z"
id:"9b77ff1e-350e-44d8-8860-15e80f4d8a22"
name:"0%"
updatedAt:"2015-02-01T13:04:17.733Z"
validFrom:"2013-07-01T00:00:00Z"
validTill:null
vatProc:0
}
]
Which is as you would expect if it where not for the date fields.
The dates are on server translated to UTC.
I know I can pass a function to parse the function to do the conversion.
I would just like to format the date's so that the regular parse would do it "right" if you know what I mean
I saw on the net that there is no "right" way and that every case what I was reading about on the net is working with conversion on the client side.
So is there really no way to tell the regular json parser that that is a date?
I have the option to convert that date-time to what ever would work on the server
ClientSide: AngularJS
ServerSide: C# WCF / json
EDIT:
The problem that I am having is that if I use for instance the ValidFrom as a model in AngularJS it is complaining that it is not a date witch it really is not
AngularJS error:
Expected `2013-07-01T00:00:00Z` to be a date
Before I send a date to the client I set the DateTimeKind property to utc
SomeObject.Date= DateTime.SpecifyKind(SomeObject.Date, DateTimeKind.Utc);
Before saving any date to the server I do:
SomeObject.Date= SomeObject.Date.ToUniversalTime();
The only requirement on the client is to use momentjs format() method in order to convert the date to ISO-8601
Following this method JSON always handles times correctly on the client (at least it has worked fine so far for me)
This helped me a lot

UTC timezone in the OK() function in .NET WebAPI C#

I have a .NET WebAPI which returns some dates as JSON.
I'm using the Ok() function which takes the C# DateTime list and convert them into a JSON array.
My requirement is to specify the timezone in any case (even +00:00)
Now, the format I'm using is:
jsonSerializerSettings.DateFormatString = "o";
which uses the ISO standard and a "Z" to specify UTC.
Unfortunately my web application doesn't understand such convention (I mean, the final "Z") and it requires a timezone offset to be present in any case.
In other words, I'd like to use a "+00:00" instead of the "Z".
How can I tell WebAPI to use such convention?
Previously I had:
jsonSerializerSettings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffzzz";
which doesn't had the timezone information.
This is not as easy as one would like - mainly, because the DateTime type is confusing at its best, and wrong at its worst.
I would recommend handling only UTC dates on the server (i.e. assuming UTC on any incoming date, saving everything as UTC and returning UTC everywhere) and letting your clients decide if they need to do something about that (e.g. convert to a local time for correct display). Then, it could be as easy as setting
jsonSerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff+00:00";
i.e. hard-coding the +00:00 there, since you know (by assumption) that it's going to be UTC.
Use System.DateTimeOffset instead of Use System.DateTime in your return statement (Ok). This will automatically append the +00:00 the the serialized string (+00:00 is assuming its a UTC point in time).
for Web API 2 and higher, I am not sure about previous versions
This is also the default date/time format for other Web API extensions like oData.

Get vs Post Auto Mapping dates C#

I am having some confusion figuring out why I am experiencing the following:
If I using jquery AJAX to "post" some Json data containing a date to an MVC controller the automapper maps the date in the format dd/mm/yyyy however if I use "get" instead the automapper seems to convert the date in to the format mm/dd/yyyy.
Does anybody know why this would be the case? When I check the json payload and querystrings for the post and get respectively they are both in the same format. The date I am using goes across as "1/7/2013" in both cases.
Regards,
Gary
Are you using a JSON serializer for the POST but a DateTime.Parse for the GET? This could yield two different results.
User DateTime.ParseExact to ensure consistent results. I.E.
DateTime.ParseExact(input, "dd/MM/yyyy HH:mm", null);

Categories

Resources