LINQ Query for checking Time duration

Rock Hitman 46 Reputation points
2021-12-22T23:32:06.757+00:00

I have a sql table which has column as below

InsuranceID              CreationDate
123                2021-04-23 10:21:47.033
4848             2020-09-13 11:21:47.033
19408           2019-06-03 12:21:47.033

I want to have a LINQ query to check, when InsuranceID is passed as a input parameter, the logic needs to check for that particular InsuranceID if the CreationDate is >24 hrs return as True else return false

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,740 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,266 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2021-12-22T23:56:04.64+00:00

    Try using in your .Where predicate e.g. .Where(item => item.CreationDate.IsPast24Hours())

    public static class DateTimeExtensions
    {
        public static bool IsPast24Hours(this DateTime dateTime) 
            => dateTime > DateTime.Now.AddHours(-24) && dateTime <= DateTime.Now;
    }
    

  2. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2021-12-24T07:58:04.15+00:00

    @Rock Hitman , you could try the following code to use linq to check if the datetime is within 24 hours.

        DataTable table=new DataTable();  
        table.Columns.Add("Id",typeof(int));  
        table.Columns.Add("CreationDate", typeof(DateTime));  
        table.Rows.Add(123,DateTime.Parse("2021-12-24 10:00 AM"));  
        table.Rows.Add(456,DateTime.Parse("2021-12-22 9:00 AM"));  
        table.Rows.Add(789, DateTime.Parse("2021-12-20 8:00 AM"));  
        int passedId = 123;  
        DateTime now = DateTime.Now;  
        DateTime yesterday = now.AddDays(-1);  
        var result = (from t in table.AsEnumerable()  
                      where t.Field<int>("Id")==passedId  
                      select (t.Field<DateTime>("CreationDate")>yesterday&&t.Field<DateTime>("CreationDate")<=now)).FirstOrDefault();  
    

    I used datatable to replace your table in the database.

    Result:

    160266-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments