简体   繁体   English

Linq 2 Sql DateTime 格式到字符串 yyyy-MM-dd

[英]Linq 2 Sql DateTime format to string yyyy-MM-dd

Basically, i need the equivalent of T-SQL CONVERT(NVARCHAR(10), datevalue, 126)基本上,我需要相当于 T-SQL CONVERT(NVARCHAR(10), datevalue, 126)

I've tried:我试过了:

  1. from t in ctx.table select t.Date.ToString("yyyy-MM-dd") but it throws not supported exception from t in ctx.table select t.Date.ToString("yyyy-MM-dd")但它抛出不支持的异常
  2. from 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. from t in ctx.table select "" + t.Date.Year + "-" + t.Date.Month + "-" + t.Date.Day但我不认为这是一个可用的解决方案,因为我可能需要能够改变格式。

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 我看到的唯一选择是使用 Convert.ToString(t.Date, FormatProvider) ,但我需要一个格式提供程序,我不确定它是否有效

FormatProvider doesn't work , String.Format doesn't work ( string.Format("{0:yyyy-MM-dd}", t.Date) throws not supported exception too). FormatProvider不工作的String.Format不工作( string.Format("{0:yyyy-MM-dd}", t.Date)抛出不支持例外太)。

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:我的 Linq 看起来像这样:

from a in context.table
where ...
select new Class
{
DateString = GetFormattedString(a.DateTimeObject)
}

And GetFormattedString just returns DateTimeObject.ToString("yyyy-MM-dd");而 GetFormattedString 只返回 DateTimeObject.ToString("yyyy-MM-dd"); This works for me!这对我有用!

Assuming that t.Date is nullable ( DateTime? ) this could be the problem, try using: 假设 t.Date为空( DateTime? ),这可能是问题所在,请尝试使用:

 
 
 
 
  
  
  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;问题是翻译成SQL; it tries to translate the .ToString() to an SQL representation, and fails.它尝试将.ToString()转换为 SQL 表示,但失败了。 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 (eg Linq to SQL Provider). AsEnumerable()将之前使用的IQueryable转换为IEnumerable ,从而停止 SQL 的生成(在 Linq 到 SQL 的情况下)或实现特定IQueryable的提供程序(例如 Linq 到 SQL 提供程序)的任何其他转换。

Note, before calling AsEnumerable() you should have completed any actions that you want to be converted to SQL and executed on the database directly.请注意,在调用AsEnumerable()之前,您应该已完成要转换为 SQL 并直接在数据库上执行的任何操作。

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 看 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.尝试创建一个对象类,您可以设置属性并让属性成为您的视图的值.. 将 LINQ 中的日期时间数据设置为字符串而不是日期时间.. 例如。

//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.我可以确认这会转化为使用 EF Core V5 和 Pomelo V5 以及 MySql 数据库的数据库操作。

The generated SQL looks something like this:生成的 SQL 看起来像这样:

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"),
             };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM