Linq 2 Sql DateTime format to string yyyy-MM-dd
Basically, i need the equivalent of T-SQL CONVERT(NVARCHAR(10), datevalue, 126)
I've tried:
from t in ctx.table select t.Date.ToString("yyyy-MM-dd")
but it throws not supported exceptionfrom t in ctx.table select "" + t.Date.Year + "-" + t.Date.Month + "-" + t.Date.Day
but i don't think it's an usable solution, because i might need to be able to change the format.
开发者_运维百科
The only option I see is to use Convert.ToString(t.Date, FormatProvider)
, but i need a format provider, and I'm not sure it works either
FormatProvider doesn't work, String.Format doesn't work (string.Format("{0:yyyy-MM-dd}", t.Date)
throws not supported exception too).
In case someone else has this problem, I solved this problem by creating a seperate function to do the date formatting for me.
My Linq looks something like this:
from a in context.table
where ...
select new Class
{
DateString = GetFormattedString(a.DateTimeObject)
}
And GetFormattedString just returns DateTimeObject.ToString("yyyy-MM-dd"); This works for me!
Assuming that t.Date
is nullable (DateTime?
) this could be the problem, try using:
from t in ctx.table select (t.HasValue ? t.Date.Value.ToString("yyyy-MM-dd") : string.Empty );
Edit: Second try
The problem is the translation to SQL; it tries to translate the .ToString()
to an SQL representation, and fails. So if you should do the following it should work:
(from t in ctx.table select t.Date).ToList().Select(d => d.ToString("yyyy-MM-dd"))
Or
(from t in ctx.table select t.Date).AsEnumerable().Select(d => d.ToString("yyyy-MM-dd"))
AsEnumerable()
transforms the previously used IQueryable
into an IEnumerable
, thus stopping the generation of the SQL (in case of Linq to SQL) or any other transfromation by the provider implementing the specific IQueryable
(e.g. Linq to SQL Provider).
Note, before calling AsEnumerable()
you should have completed any actions that you want to be converted to SQL and executed on the database directly.
Is there a reason to perform the conversion on the database side? Whenever I run into this type of situation, I tend to just allow the database to give me the raw data and then do the massaging and manipulation within the application. Depending on the volume of requests to the database server and the size of the result set, I don't want to tie up processing and response time doing data conversions that can be handled by the client.
look no.3
var user = (from u in users
select new
{
name = u.name,
birthday = u.birthday.Value
})
.ToList()
.Select(x => new User()
{
name = x.name,
birthday = x.birthday.ToString("yyyyMMdd") // 0埋めされるよ
});
Try to create an object class that you can set the properties and let the properties be the value for your view.. Set the datetime data from LINQ as string and not datetime.. ex.
//Property class
[DataContract()]
public class Info
{
[DataMember(Name = "created_date")]
public string CreateDate;
}
//Controller
var date = from p in dbContext.Person select p;
CreateDate = Convert.ToDateTime(p.create_date).ToString("yyyy-MM-dd");
Hope you'll try this.. I have this on my past applications and this is what I did.
I had a global search function on a quoting website from which I wanted to be able to search on all details of a quote (quote references, vehicle details, customer details etc.) including the created dates using only the single input text value:
This means that I definitely don't want to enumerate the results before attempting to cast the date to the appropriate string format.
In an attempt to do this, I've come up with the following:
// this is obviously only a fragment of my actual query
_context.Quotes
.Where(q => string.Concat(
q.DateCreatedUtc.Day < 10 ? "0" : "",
q.DateCreatedUtc.Day,
"/",
q.DateCreatedUtc.Month < 10 ? "0" : "",
q.DateCreatedUtc.Month,
"/",
q.DateCreatedUtc.Year
)
.Contains(searchTerm));
I can confirm this translates to a database operation using EF Core V5 and Pomelo V5 with a MySql database.
The generated SQL looks something like this:
WHERE
LOCATE(@search_term, CONCAT(
CASE WHEN EXTRACT(DAY FROM `quote`.`date_created_utc`) < 10 THEN '0' ELSE '' END,
CAST(EXTRACT(DAY FROM `quote`.`date_created_utc`) AS CHAR),
'/',
CASE WHEN EXTRACT(MONTH FROM `quote`.`date_created_utc`) < 10 THEN '0' ELSE '' END,
CAST(EXTRACT(MONTH FROM `quote`.`date_created_utc`) AS CHAR),
'/',
CAST(EXTRACT(YEAR FROM `quote`.`date_created_utc`) AS CHAR)
)) > 0
This entire query has turned into a bit of a Frankenstein though and I am seriously questioning the value of allowing users to search on the dates.
try this
var select = from s in db.Table
where s.date == someDate
select new
{
date = DateTime.Parse(s.date.ToString()).ToString("yyyy-MM-dd"),
};
精彩评论