piowtarn piowtarn - 2 months ago 41
C# Question

Dapper return reversed date format

Dapper returns date type column in different format than it is stored in database.

format in database ----> 2012-05-19 15:27:00.000

dapper returns --------> 19-05-2012 15:27:00.000

var l = this.db.Query<myObject>("select id, received from myTable where( received between @d1 and @d2)",
new { @d1 = d1, @d2 = d2, }).ToList();

string d1 = 2011-01-18 00:00:00
string d2 = 2014-07-18 23:59:59

public class myObjectIs
{
public string id { get; set; }
public string received { get; set; }

}


received - datatime type columm

Has Dapper got predefined format of date type to return?
If yes, how to change it?

Thanks.

Answer

The problem appears to be that you are using a string for received, instead of a DateTime. Dates/times do not have a format, until you actually force them to become a string - at which point they are no longer dates/times. A date/time is just a number.

As a last ditch effort, if all inbuilt conversions are exhausted, dapper uses Convert.ChangeType to thunk between types. This will cause regular ToString() to be used in this case. If you don't want this (and you shouldn't want this): declare received to be a DateTime:

public DateTime received { get; set; }

Likewise, from comments:

d1 and d2 are strings

They should not be; they should be DateTime too:

DateTime d1 = ..., d2 = ...

or at the very least, you should parse it inside your data access code:

new { d1 = [someparse(d1)], @d2 = [someparse(d2)], }

where [someparse] is probably something involving DateTime.Parse or DateTime.ParseExact

Comments