I have a OrderEntity and OrderItemEntity. I have simplified as shown below to describe the problem.
OrderEntity:
public class OrderEntity
{
public DateTime OrderDate { get; private set; } = DateTime.Now;
public DateTimeOffset CreatedAt { get; protected set; }
}
OrderItemEntity:
public class OrderItemEntity
{
public DateTime? StartDate { get; private set; }
public DateTimeOffset CreatedAt { get; protected set; }
}
Here is the request localisation setup in Program.cs,
Program.cs:
app.UseRequestLocalization(options =>
{
var supportedCultures = new[] { "en", "en-IN", "en-US" };
options.SetDefaultCulture("en-IN");
options.AddSupportedCultures(supportedCultures);
options.AddSupportedUICultures(supportedCultures);
options.ApplyCurrentCultureToResponseHeaders = true;
})
Whenever order is created, OrderDate will be automatically DateTime.Now and OrderItem StartDate Local DateTime will be passed as input from user and Entity Framework Core will intercept all entities before save and set CreatedAt to DateTimeOffset.Now. All the request will have Accept-Language header set and in this case User is from India, so it will be en-IN
The application runs in on-prem with postgres db in on-prem and on cloud with postgres db in cloud separately. For the same input the data stored in databases are different and this makes difficult to query data and show to user.
Now when the Order is created from user via browser running with English India language on 02 August 2023 02:00 PM, below is the difference observed in data stored.
| DBType | C# Type | Field | Input | On Prem (English India Machine) | AWS Cloud |
|---|---|---|---|---|---|
| timestamp with out timezone | DateTime | StartDate | 01-08-2023 00.00 (01 August 2023 12.00 AM) |
01-08-2023 00.00 (01 August 2023 12.00 AM) |
31-07-2023 18.30 (31 July 2023 06.30 PM) - Different from user input |
| timestamp with out timezone | DateTime | OrderDate | - | 02-08-2023 02.00 (02 August 2023 2.00 PM) - same as user created |
02-08-2023 08.30 (02 August 2023 8.30 AM) - same as user created but Offset Difference |
| timestamp with timezone | DateTimeOffset | CreatedAt | - | 02-08-2023 02.00 +5.30 (02 August 2023 02.00 PM) - Same as user created date |
02-08-2023 02.00 +5.30 (02 August 2023 02.00 PM) - Same as user created date |
I now understood that DateTime needs to be persisted in UTC in database. But wondering how for a given request, in AWS Cloud, OrderDate (DateTime.Now) is different from CreatedAt (DateTimeOffset.Now).
So now which is correct here?
CreatedAt-DateTimeOffset.Nowis correct way to store? or I need to change it toDateTimeOffset.UtcNow?OrderDate-DateTime.Nowneeds to be changed toDateTime.UtcNowor column itself should be changes toDateTimeOffsetand storeDateTimeOffset.UtcNow?StartDate- User Input (Local Time) - gets stored as UTC DateTime in DB - What should be done here? This also needs to be changed toDateTimeOffsetColumn?