0

Say I create a DateTimeOffset value like this:

var dt = DateTimeOffset.UtcNow;

And I want to store this value in SQL Server using EF Core code-first. How do I remove the milliseconds portion, so that the value stored in SQL Server becomes 2020-09-08 14:51:00 +00:00 instead of 2020-09-08 14:51:00.4890984 +00:00?

Mike Hawkins
  • 2,144
  • 5
  • 24
  • 42
  • 5
    I don't know about EF core but in SQL Server you can have your column defined as a `DateTimeOffset(0)` which means no fractional seconds. – Zohar Peled Sep 08 '20 at 15:07
  • 1
    as Zohar said, you should configure the property on your model by specifying the DateTimeOffset(0) type, either through attributes, or through the fluent configuration – ESG Sep 08 '20 at 15:12
  • Thanks. I configured it through fluent api. – Mike Hawkins Sep 08 '20 at 15:18
  • 1
    Feel free to post the solution as a self answer, so that other users might benefit from your experience. – Zohar Peled Sep 09 '20 at 09:20

3 Answers3

1

I agree with @Zohar Peled. Define your data as it is supposed to be.

other than that, In c# you can truncate date in this way:

dt.AddTicks( - (dt.Ticks % dt.TicksPerMilliseconds));

this post has more general approach.

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • 1
    Thanks for the response and the reference. I ended up using Zohar/ESG's approach to configure it at the database level. – Mike Hawkins Sep 08 '20 at 15:18
1

Based on @Zohar suggestion using Data Attributes on your Model binded to EF:

    [Column(TypeName = "datetimeoffset(0)")]
    public DateTimeOffset Date { get; set; }
Jonathan Ramos
  • 1,921
  • 18
  • 21
0

A simple way is to use a value converter.

The code could look like this (using the answer from How to truncate milliseconds off of a .NET DateTime for the actual conversion logic):

public class YourContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<YourEntity>()
            .Property(e => e.YourProperty)
            .HasConversion(
                v => v.AddTicks(-(dateTime.Ticks % TimeSpan.TicksPerSecond));,
                v => v);
    }
}

Of course you can also explicitly define and then reuse the value converter and you can also apply it to all properties of a certain type like 'DateTimeOffset', by iterating over the entities and their properties via ModelBuilder.

lauxjpn
  • 4,749
  • 1
  • 20
  • 40