基本上,我需要相当于 T-SQL CONVERT(NVARCHAR(10), datevalue, 126)
我试过了:

  • from t in ctx.tableselect t.Date.ToString("yyyy-MM-dd")但它抛出不支持的异常
  • from t in ctx.tableselect "" + t.Date.Year + "-" + t.Date.Month + "-" + t.Date.Day但我不认为这是一个可用的解决方案,因为我可能需要能够更改格式。

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

    FormatProvider 不 workString.Format 不起作用( string.Format("{0:yyyy-MM-dd}", t.Date) 也抛出不支持的异常)。

    最佳答案

    如果其他人有这个问题,我通过创建一个单独的函数来为我进行日期格式化来解决这个问题。

    我的 Linq 看起来像这样:

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

    而 GetFormattedString 只返回 DateTimeObject.ToString("yyyy-MM-dd");
    这对我有用!

    关于c# - Linq 2 Sql DateTime 格式到字符串 yyyy-MM-dd,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2428128/

    10-13 06:24