Date value is getting changed when saving to database

c# date datetime entity-framework-core sql-server


I am saving two datetime variables to a SQL database (hosted in Azure) table using Entity Framework Core. Somehow when I query the database after saving, I noticed that the datetime values have changed. You can see the initial values just before saving below.

Code with values pinned

After saving, it shows in the database as follows

SQL Table values

I read through several technical documentation to find the factors which could effect on this. Still, I did not find anything interesting.

Could you please help me to understand what’s behind this data change? I am pretty sure that there is no any stored procedure or some any other script that could change these dates either.

// step 3: update tblStudent
var tblStudentEntityToUpdate = await _applicationDbContext.Value.StudentApplications.FirstOrDefaultAsync(x => x.StudentID == vm.StudentID);
vm.GuardianID = guardianId;

await _applicationDbContext.Value.SaveChangesAsync();
9/18/2019 4:03:39 AM

Popular Answer

As zaitsman has mentioned in his comment, the reason is that you are working with DateTimes that are in local format. Regardless of the datacenter location chosen, your SQL Azure server is set to the UTC timezone. AFAIK this can't be changed.

Storing DateTimes as UTC is always recommended, since this avoids any problems where you write in a local time and then read it with a different timezone assumption.

From what I understand, your application should be working fine, since your application will read these values back and store them correctly as UTC DateTimes, and you might then call DateTime.ToLocalTime if you want to present this info for a certain timezone.

9/18/2019 5:21:21 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow