question

InigoMontoya-1790 avatar image
0 Votes"
InigoMontoya-1790 asked TimonYang-MSFT commented

Return All Records from Last 15 Minutes

Hello - trying to work with Linq...

Will this statement return all records from the last 15 minutes? I ask because DateTimeCreated is in a format like this 2021-06-25 13:47:19.217

This is my full statement, can someone assist me here in validating this will return all records from the last 15 minutes or helping me with updated code that will do that?

 _databaseRepository.SelectList<Table>(sp => (sp.userId == 18 || sp.userId == 20) && sp.DateTimeCreated >= DateTime.Now.AddMinutes(-15));
dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@InigoMontoya-1790
It is possible to filter the time in this way. Did you encounter any problems when using this code?

0 Votes 0 ·

1 Answer

karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered

Hello,

To determine if your code works properly, write a unit test method which has mocked up data and use a class which mocks DateTime.Now e.g.

 using System;
 using System.Threading;
    
 namespace PayneUnitTestProject.Classes
 {
    
     public class DateTimeProvider : IDisposable
     {
         private static readonly AsyncLocal<DateTime?> _injectedDateTime = new();
    
    
         public static DateTime Now => _injectedDateTime.Value ?? DateTime.Now;
    
         public static IDisposable InjectActualDateTime(DateTime actualDateTime)
         {
             _injectedDateTime.Value = actualDateTime;
    
             return new DateTimeProvider();
         }
    
         public void Dispose()
         {
             _injectedDateTime.Value = null;
         }
     }
 }

Usage

 using (DateTimeProvider.InjectActualDateTime(new DateTime(2021, 6, 6, 2, 12, 0)))
 {
     // run your code against mocked data
 }


Or validate using a SELECT in SSMS e.g. using DATEADD(minute, -15, GETDATE()) in the WHERE condition

In closing, unit test take time to put together but well worth the effort as they are meant to validate or invalidate your code.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.