Linq 2 Sql DateTime格式到字符串yyyy-MM-dd [英] Linq 2 Sql DateTime format to string yyyy-MM-dd
问题描述
基本上,我需要相当于T-SQL CONVERT(NVARCHAR(10),datevalue,126)
Basically, i need the equivalent of T-SQL CONVERT(NVARCHAR(10), datevalue, 126)
我尝试过:
-
from ct in ctx.table
select t.Date。 ToString(yyyy-MM-dd)
但它不支持异常 -
from ct in ctx.table
选择+ t.Date.Year + - + t.Date.Month + - + t.Date.Day
但我不认为这是一个可用的解决方案,因为我可能需要更改格式。
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.
我看到的唯一选项是使用 Convert.ToString(t.Date,FormatProvider)
,但我需要一个格式提供程序,我不确定它是否工作
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不工作 , String.Format 无效( string.Format({0:yyyy-MM-dd},t.Date)
th行不支持异常)
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.
我的Linq看起来像这样:
My Linq looks something like this:
from a in context.table
where ...
select new Class
{
DateString = GetFormattedString(a.DateTimeObject)
}
而GetFormattedString只返回DateTimeObject.ToString(yyyy-MM-dd);
这适用于我!
And GetFormattedString just returns DateTimeObject.ToString("yyyy-MM-dd"); This works for me!
这篇关于Linq 2 Sql DateTime格式到字符串yyyy-MM-dd的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!