LINQ如何计算天差 [英] How to calculate days difference LINQ

查看:81
本文介绍了LINQ如何计算天差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



如何计算两个日期的日期差异并获得最终的差额。



我尝试使用以下代码:

Hello,

How to calculate the date difference of two dates and get the final difference amount.

I tried using following code:

  var tdays = from items in Vals
                           select new
                           {
                               days = 
                               (
                               DbFunctions.DiffDays(items.maxdate, items.mindate )
                               )
                           };

But I am getting error:
<pre lang="C#">base = {&quot;This function can only be invoked from LINQ to Entities.&quot;}</pre>

推荐答案

基本上,你可以减去两个DateTimes并得到一个TimeSpan:

Basically, you can subtract two DateTimes and get a TimeSpan as a result:
DateTime start = new DateTime(2015, 12, 1, 20, 0, 0);
DateTime end = new DateTime(2015, 12, 2, 4, 30, 10);
TimeSpan span = end - start;
int hours = span.Hours; // hours = 8;
int minutes = span.Minutes; // minutes = 30;
int seconds = span.Seconds; // seconds = 10;
int days = span.Days; // days = 0;
double totalDays = span.TotalDays; // totalDays = 0.35428241





您可以在此处找到有关TimeSpan结构的更多信息:

MSDN:TimeSpan结构 [ ^ ]



要回答您的问题,我们需要知道您的<$ c类型$ c> Vals 变量是枚举;如果这种类型不是常见类型(即,您自己定义),我们需要知道如何定义其maxdate和mindate成员。



You can find find more informations on TimeSpan structure here:
MSDN: TimeSpan Structure[^]

To answer to your question, we would need to know which type your Vals variable is an enumeration of; and if this type is not a common one (i.e., you defined it yourself), we would need to know how its maxdate and mindate members are defined.


试试以下内容:



Try following:

var days = from items in Vals
            select new
            {
                days = items.maxdate - items.mindate
            };

foreach (var day in days)
{
    Console.WriteLine(day.days.TotalDays);
}


这样做 -

Rather do it this way-
DateTime oldDate = new DateTime(2015,11,2);
DateTime newDate = DateTime.Now;
TimeSpan ts = newDate - oldDate;
int differenceInDays = ts.Days;

Console.WriteLine("Total days: {0} ", differenceInDays);







-KR




-KR


这篇关于LINQ如何计算天差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆