简体   繁体   中英

Date value is getting changed when saving to database

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;

_applicationDbContext.Value.Entry(tblStudentEntityToUpdate).CurrentValues.SetValues(vm);
await _applicationDbContext.Value.SaveChangesAsync();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM