简体   繁体   English

在LINQ中将datetime2转换为字符串(“ dd / MM / yyyy”)

[英]Convert datetime2 to string(“dd/MM/yyyy”) in LINQ

I have a datetime2 column in the database.I'm trying to fetch that from database and I want to display it in the view as string. 我在数据库中有一个datetime2列,我试图从数据库中获取它,我想在视图中以字符串形式显示它。

I tried: dt.ToString("dd/MM/yyyy"); 我尝试过: dt.ToString("dd/MM/yyyy");

But it gave an error. 但是它给出了一个错误。

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code EntityFramework.SqlServer.dll中发生类型为'System.NotSupportedException'的异常,但未在用户代码中处理

Additional information: LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression. 附加信息:LINQ to Entities无法识别方法'System.String ToString(System.String)',并且该方法无法转换为商店表达式。

I tried String.Format("{0:y yy yyy yyyy}", dt); 我试过了String.Format("{0:y yy yyy yyyy}", dt); also, even this throwed an error. 另外,即使这样也会引发错误。

错误

you can check this site : click here 您可以检查此站点: 单击此处

DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

and Basically, in entityframework has no idea how to translate an object of System.Threading.Tasks.Task to a SQL statement.you can use : 基本上,在entityframework中不知道如何将System.Threading.Tasks.Task对象转换为SQL语句。您可以使用:

SqlFunctions.StringConvert(dt)

or before using tostring(), use .tolist(): 或在使用tostring()之前,使用.tolist():

.ToList().select(p=>new{date=dt.ToString()});

I think I realize your problem, after you posted the screenshot. 发布截图后,我想我意识到了您的问题。 Some functions aren't allowed to run inside the linq, as linq needs to translate them to sql. 某些函数不允许在linq 运行,因为linq需要将它们转换为sql。

Since I can't copy paste your code with my modifications (you need to perform the date formatting outside the linq statement, whether using a foreach loop, or any other method). 由于我无法复制并粘贴修改后的代码(您需要在linq语句之外执行日期格式设置,无论是使用foreach循环还是任何其他方法)。 A rough idea: 一个大概的想法:

allclient = (from ....
             select new AllClient()
             {
              ...
              PurchaseDT = "",
              PurchaseDate = k.PurchaseDate, //the formatting will be done later
             }
foreach (AllClient c in allclient)
      c.PurchaseDT = String.Format("{0:y yy yyy yyyy}", c.PurchaseDate); //or whatever other formatting you want

where PurchaseDate is of type DateTime and PurchaseDT is of type string. 其中PurchaseDate的类型为DateTime,而PurchaseDT的类型为string。

First save the value coming from db to a datetime variable and later loop through the list using a foreach loop,convert the datetime variable into string and assign it to the string variable. 首先将来自db的值保存到datetime变量,然后使用foreach循环遍历列表,将datetime变量转换为string并将其分配给string变量。

Updated 更新

The only way will involve you adding one more variable to the AllClient class, if you can. 唯一的方法是,如果可以的话,您需要向AllClient类中再添加一个变量。 This will be a DateTime to temporarily store the date, with another one as string (as shown in the code snippet above), which will be updated with the formatted date after the linq statement. 这将是一个DateTime来临时存储日期,另一个日期作为字符串(如上面的代码片段所示),该日期将在linq语句后使用格式化的日期进行更新。

OR 要么

Keep a single DateTime PurchaseDT , and instead of formatting it in linq or immediately afterwards, only format it when you are displaying it. 保留单个DateTime PurchaseDT ,而不是在linq或之后立即对其进行格式化,而仅在显示时对其进行格式化。 For example, if you're displaying the records on a table of some kind, while displaying the date column, do the formatting on PurchaseDT there. 例如,如果要在某种类型的表上显示记录,同时显示日期列,请在此处对PurchaseDT进行格式化。

try this : 尝试这个 :

dt.ToString("d");

please note : the "d" format is Culture aware, but it gives you short date pattern. 请注意:“ d”格式可识别文化,但可以提供短日期格式。

DateTime dt = DateTime.ParseExact(<datetime string from db>, <format of date in Datetime string from db>, CultureInfo.InvariantCulture);
string formattedDate = dt.ToString("dd/MM/yyyy",CultureInfo.InvariantCulture);

First you have to convert the datetime string to a DateTime object then you can Convert to required format. 首先,您必须将datetime字符串转换为DateTime对象,然后才能转换为所需格式。 The overload of ToString you are using is valid for DateTime object and not for a String object.That's the reason for the error 您正在使用的ToString的重载仅对DateTime对象有效,而对String对象无效,这就是错误的原因

You can use this for the View : 您可以将其用于View:

@model.RegisteredDate.ToString("dd MMMM , yyyy")

This will give 21 August , 2016 of Format. 格式为21 August , 2016
If you refer 21 Aug , 2016 then just use "MMM" 如果您引用21 Aug , 2016则只需使用“ MMM”

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

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