Agamemnon
Agamemnon

Reputation: 607

Change DateTime format when using Entity Framework

How to change the DateTime format when using Entity Framework?

In my database table, the column sb_ActivityDate is of 'datetime' datatype.

enter image description here

Here is how I get that column's value:

var query = context.CPDActivities.AsQueryable();

if (!(member.MemberID == Guid.Empty))
{
    query = query.Where(e => e.sb_MemberContactId == member.MemberID).OrderBy(e=>e.sb_ActivityDate).ThenBy(e => e.CreatedOn);
} 
else
{
    return null;
}

And stepping through the code can see that the 'sb_ActivityDate' value is now in M/d/yyyy format where I need dd/MM/yyyy.

enter image description here

The property for the date created by Entity Framework database first:

        public Nullable<System.DateTime> sb_ActivityDate { get; set; }

Edit 1: my system date format:

enter image description here

Edit 2:

Edit 3:

enter image description here

Edit 4:

Added a simple test textbox with date:

tb_dateTest.Text = DateTime.Now.ToString();

enter image description here

This seems to show the CMS culture is not causing the issue. Something else is formatting the date.

Upvotes: 0

Views: 3012

Answers (1)

Mark Cilia Vincenti
Mark Cilia Vincenti

Reputation: 1614

The problem relates to regional/culture settings, and it seems the ones Visual Studio is working under are not the same as the database. Since VS2015, you can check what format the debugger will be working under by checking the value for Thread.CurrentThread.CurrentCulture

If you want to format the date/time to something specific for displaying the date/time, such as from a web application where typically users could have different culture settings, then you need to convert it to a string at the point you're displaying the date/time.

Upvotes: 1

Related Questions