Typing

Asked

Viewed 74 times

2

I am creating a database and in it has a field that receives a date, I would like it to appear only the date. If I use the type datetime comes with the time too. And in SQL Server you have the type option date, but when it comes to doing it in C# there’s no such thing, there’s only datetime.

How can I remove the time in C#?

Or you can use the guy datetime and remove the time on SQL Server?

inserir a descrição da imagem aqui

  • Are you using any ORM framework, like Entity?

  • I’m using the Entity framework

2 answers

4


As you commented that you are using the Entity Framework, you can do one of the following:

1 - Assigning type in Model:

[Column(TypeName="Date")]
public DateTime Data { get; set; }

2 - Using the Fluent API, adding the following code in the method OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Titulo>().Property(p => p.Data).HasColumnType("Date");
}

Remembering that you need to add import:

using System.ComponentModel.DataAnnotations.Schema;

After that, recreate or change your table if you are using Migrations.

2

You must use the property Date:

var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;

The variable date will contain the date, part of the time will be with the value 00:00:00.

More information about the property Date here.


It also depends on how you insert the records into the database and how the date column is configured in SQL. Ideally it will be of the type Date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.