Finding Yesterday in SQL and C#

Here's something that comes up often in forums - How To Find Yesterday in SQL or C#. Piece of cake, if you know how, but tricky if you don't. And especially tricky to get the right value if you are not clear on the requirement.

The current time (in C#), as I type, is 12/07/2010 19:21:36. That's achieved by using Console.WriteLine(DateTime.Now); on a box with UK regional settings. According to SQL Server, it's now 2010-07-12 19:21:36.957. That's obtained through executing the following query: SELECT GetDate(). So we know that DateTime.Now and GetDate() are the ways to get the current date and time in C# and SQL respectively.

In C#, there is an AddDays() method that takes an integer. That integer can be negative, so the following will obtain the date and time for yesterday: Console.WriteLine(DateTime.Now.AddDays(-1));. SQL has a similar function: DateAdd(). This takes an interval or datepart as they are known, an integer (which can also be negative) and a datetime. There are a number of accepted values for the datepart argument, which can be found here. To get the same result as the preceding C# code, you would simply use SELECT DATEADD(d, -1, GetDate()).

So far so good, if all you need is the date and time for 24 hours ago (11/07/2010 19:21:36). However, and here's the rub - often, you might want to obtain all events that happened yesterday (or the day before today) from a collection or a database table. If you were to use the preceding SQL example in a statement like this:

SELECT * FROM Table1 WHERE EventTime < DATEADD(d, -1, GetDate())

you will get all items that have an EventTime value before yesterday at 19:21:36. All items that occured after that time will not be included. Not quite what you would expect, maybe. The same problem exists if you are querying a collection of C# objects using DateTime.Now.AddDays(-1) as the basis for the comparison. Try this example code:

var times = new List<DateTime>();
for (var i = 1; i <= 48; i++)
{
  times.Add(DateTime.Now.AddHours(-i));
}


foreach (var t in times.Where(t => t < DateTime.Now.AddDays(-1)))
{
  Console.WriteLine(t);
}

Console.ReadLine();

All it does is build a List<DateTime> with items 1 hour apart, going backwards from now. However, it will only select those items that have a value prior to 19:21:36 yesterday, which leave some events from yesterday still untroubled - ie those between 19:21:36 and midnight.

It's the pesky time part that gets in the way, so that needs to be changed to 00:00:00 or midnight. Previously, this article showed how to do that with C#, until Steve contributed his comment below, pointing out that DateTime.Now.Date gives us exactly that. However, in SQL, the solution is to change the datetime to a string:

[C#]
var yesterday = DateTime.Now.Date;
foreach (var t in times.Where(t => t < yesterday))
{
  Console.WriteLine(t);
}
[SQL]
SELECT * FROM Table1 WHERE EventTime < CONVERT(varchar(10), GETDATE(), 101)

As someone once said: Hope This Helps.

 

Date Posted: Monday, July 12, 2010 9:27 PM
Last Updated: Tuesday, July 20, 2010 6:28 AM
Posted by: Mikesdotnetting
Total Views to date: 14986

4 Comments

Sunday, July 18, 2010 2:47 AM - Mike

Thanks man!, actually used that snippet concept today lol

Monday, July 19, 2010 9:36 PM - Steve

what about:

var yesterday = DateTime.Now.Date;

Tuesday, July 20, 2010 5:25 AM - Mike

@Steve,

Yes - that will do it :o)

Wednesday, August 11, 2010 9:28 PM - dotnetcoder

Simple and very informative!
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...