how to save and compare datetime values in C# and core?

c# datetime entity entity-framework-core


I'm writing a web app using core and entity framework core; i want to set current date and time for db objects when they are created and later i need to compare them with datetimes that users specified. my app target users is local to my country. is DateTime.Now suitable and reliable for me? my local calender is 'Persian jalali' and DateTime.Now returns a jalali datetime for me.. i'm confused and unsure, can i use jalali datetimes everywhere in my app (such as comparisons) or i should convert them to Gregorian or UTC (or other approach)?

 // a sample datetime setting for an object
_stateService.Create(new State{
 Name = "sample",
 CreateDateTime = DateTime.Now

// a sample datetime setting for added entities to entity framework core
var now = DateTime.Now;

var addedEntries = ChangeTracker.Entries()
           .Where(x => x.State == EntityState.Added);

foreach (var addedEntry in addedEntries)
   addedEntry.Property("CreateDate").CurrentValue = now;

// a sample comparison i used with linq
// **'from' and 'to' must be 'Jalali' or 'Gregorian'?**
var res= _paymentService.GetPayments()
.Where(p => p.CreateDate >= from && p.CreateDate <= to).ToList();

entity framework core returns objects with datetime values in Jalali..

5/8/2019 7:49:31 AM

Popular Answer

The best approach will be to Save all the dates in UTC format yourDateTime.ToUniversalTime()

You should write each client location or utc difference depending on your logic. for example in new york its UTC−05:00

You have lists of utc differences online (also apis if needed):

The complexity really depend on the your logic

5/8/2019 7:55:51 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