0

I am calling an API controller post method from client with a model that contains datetime properties, but when the request is received at the API controller, the datetime value automatically get changed.

My client application is a desktop application and running under the Indian timezone and API is hosted on a server that is in the EST timezone.

When my client application sends

"TransDate": "2023-03-26T00:00:00+05:30"

it is changed to

"TransDate":"2023-03-25T14:30:00-04:00"

in the API controller.

My client desktop application can run under multiple time zones and the datetime value sent from client location is in the local time zone that should be unchanged when it receives to at API controller.

One alternative I can think of to change DateTime type to DatetimeOffSet but problem is: I have to change code in multiple places as it exists throughout the application, I am looking for any common solution to prevent this conversion.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
  • In your model, how is `TransDate` declared? Is it `public DateTime TransDate { get; set; }`, or something else like `public DateTimeOffset TransDate { get; set; }` or `public string TransDate { get; set; }` – dbc Mar 26 '23 at 14:46
  • Assuming it's `DateTime`, then you probably can't do what you want because `DateTime` **does not include any timezone info**. See [Get timezone from DateTime](https://stackoverflow.com/q/576740). From the [source](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/DateTime.cs#L156) all it contains is a `private readonly ulong _dateData;` which holds the number of ticks in bits 01-62 and the kind flag in bits 63-64. So a JSON string like `"2023-03-26T00:00:00+05:30"` actually combines information from the original `DateTime` with the system time zone. – dbc Mar 26 '23 at 17:08
  • Then during deserialization the model binder has to map that "2023-03-26T00:00:00+05:30" string to a `DateTime`, and since `DateTime` has no time zone info it the binder chooses to preserve the UTC value of the serialized `DateTime` by mapping it to the local time zone on the receiving system. – dbc Mar 26 '23 at 17:12
  • 1
    But if you want to override that behavior and do something else like ignore the time zone and preserve the relative local time, you can change Json.NET's behavior as explained in [DateTimeZoneHandling setting](https://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm) and [Why does Json.NET DeserializeObject change the timezone to local time?](https://stackoverflow.com/q/11553760). Or switch to `DateTimeOffset` or some 3rd party type like [`ZonedDateTime`](https://nodatime.org/2.2.x/api/NodaTime.ZonedDateTime.html). – dbc Mar 26 '23 at 17:14

0 Answers0