…Or maybe tomorrow’s.
You would think it would be easy. After all, getting today’s date is normally fairly easy.
However, for so many languages, this can be really challenging. It often requires the programmer to know what the month is, and decide, is today at the beginning of the month (in which case we have to go to the previous month, but what is the last day of that month?) or the end of this month (in which case tomorrow has to update the month, but at least you know it’s the first.)
This doesn’t even begin to handle first/last day of the year.
Let’s see how to get yesterday’s date, using C#.
One of the key things to know, is how to get today’s date.
DateTime today = DateTime.Now;
If we are going to get yesterday’s date, we need to know that C# gives us several built-in methods to add time (days, months, etc) to our date. However, it doesn’t give us any methods to subtract time… or so it would seem.
We can pass in a negative value to the method .AddDays, and essentially “subtract” from the date, to get yesterday.
DateTime yesterday = today.AddDays((double) -1);
We can then convert this to an easier to display string, using one of the many predefined “ToString” methods. Such as:
string strYesterday = yesterday.ToShortDateString();
Of course, we can always chain this, so it is easier to work with. For example we can do something like:
// define yesterday - as a string string yesterday = DateTime.Now.AddDays((double)-1).ToShortDateString();
Getting Yesterday’s Date was originally found on Access 2 Learn