I am using ASP.net core 5 and angular 15.0 for backend and frontend respectively. When a date property is got from the user on the client side (e.g. Sun Jan 01 2023 21:27:11 GMT 0330 (XXX Standard Time)), before posting it to the server as an object, it is converted to ISO format (i.e. it is converted to : 2023-01-01T17:57:11.528Z) and sent to the server as an object to save in database. When retrieving the same date from the server, it will be displayed one day earlier. The OffsetZone is -210 (-3:30'). How to add the time offset to the received Date property by controller action (i.e. Received Date property is converted to 2023-01-01T21:27:11, Be exactly the same as the local Date value) in the action before it is saved to the database? best regards
CodePudding user response:
We standardised our comms between front and back end a while ago.
The main point being the same as you are already doing - sending/receiving the dates in UTC ISO format. Doing this gives you a clear, shared based for each to work on as desired.
The second part is to use DateTimeOffset
in our models instead of the more basic DateTime
.
This parses the ISO string, just like DateTime
does, but gives you accessor options for x.LocalDateTime
to have it pull out a DateTime
value according to the server's local time (which it sounds like what you want) as well as retrieving the base UTC time for it with x.UtcDateTime
if you so desire.
E.g.
public class SomeInput {
[Required]
public string SomeProp { get; set; }
[Required]
public DateTimeOffset TheTime { get; set; }
}
public class SomeController : ... {
[HttpPost]
public Task<IActionResult> SomeAction(SomeInput input) {
var utc = input.TheTime.UtcDateTime;
var serverLocal = input.TimeTime.LocalDateTime;
// ...
}
}
In this way, you can make sure you pass through the serverLocal
value rather than the UTC value to your services so it's all working on your server's local time.