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
Related
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()
I have a use case that I'm not sure how to solve in a nice way.
I'm currently developing a .Net Core WebApi that is receiving data from various current systems, from a cross the whole world. Which I then process and lastly I commit it to SAP through oData endpoint.
The problem I'm having is on of parameters I'm receiving in the body payload, is a DateTime. Previous I have not have any issues. But not long ago I started getting data from a other system which deliverers it in a slightly differently way.
Previously this was the format I got: 2020-09-16T16:30:00 not problem with it. But the new system looks like this: 2020-09-16T16:00:00 -05:00 Could also end in +08:00.
The problem I'm facing is that SAP needs to get in local time. But in the my code it converts this: 2020-09-16T16:00:00 -05:00 to 2020-09-16T23:00:00 when I see the incoming payload in the controller.
I have searched quite a bit to find a solution. But 99% only suggest using UTC time, which is not a option for me.
Another option is to use DateTimeOffset, which I have tried but can't the time conversion to use localTime.
My question is. Are it not possible to custom convert to strip the timezone before it hits the controller?
Generarally when you're working with datetime data that includes offsets for time zone the DateTimeOffset type is a good place to start. The sample string 2020-09-16T16:00:00 -05:00 can be passed to DateTimeOffset.Parse() to get a correct DTO value with timezone information attached. From there you can get the local time, UTC time or a DateTime value with the timezone stripped.
string source = "2020-09-16T16:00:00 -05:00";
string fmt = #"yyyy-MM-dd\THH:mm:ss zzz"
// Same as input
Console.WriteLine(DateTimeOffset.Parse(source).ToString(fmt));
// Adjusted to your local timezone
Console.WriteLine(DateTimeOffset.Parse(source).ToLocalTime().ToString(fmt));
// DateTime portion of the source, timezone offset ignored
Console.WriteLine(DateTimeOffset.Parse(source).DateTime.ToString());
Getting the UTC time is simple too via the UtcDateTime property.
It sounds like what you want is the last one - just the date and time from the inputt string with the timezone offset stripped. If you just want the corresponding local time then DateTime.Parse should give that to you directly.
The JsonSerializer class doesn't support this format for DateTimeOffset so you might have some trouble getting it converted before hitting your controller. In that case you'd need to accept a string and do the conversion by hand in your code. You also might need to investigate the TryParseExact method.
Use DateTime.Parse() , for example
string timeInString1 = "2020-09-16T16:00:00 -05:00";
DateTime moment1 = DateTime.Parse(timeInString1);
string timeInString2 = "2020-09-16T16:00:00 +08:00";
DateTime moment2 = DateTime.Parse(timeInString2);
string timeInString3 = "2020-09-16T16:30:00";
DateTime moment3 = DateTime.Parse(timeInString3);
but momen1, momen2, or moment3 is non-timezone awareness value.
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.
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.
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);