Open In App
Related Articles

C# Program to Get the Date of Yesterday Using TimeSpan Method

Improve Article
Improve
Save Article
Save
Like Article
Like

TimeSpan is a struct that is used to represent time interval which is used to measure the positive and negative number of minutes, hours, days. It is also used to represent the time of the day only when the time is unrelated to some specified date. In this article, we will find yesterday’s date using the TimeSpan struct. 

Syntax:

TimeSpan variable_name = new TimeSpan();

We can get the day, month, and year of a particular date using the following methods:

  • datetime.Day: It is used to find the day represented by this instance.
  • datetime.Month: It is used to find the month of the date represented by this instance.
  • datetime.Year: It is used to find the year of the date represented by this instance.

Example:

C#




// C# program to find the date of 
// yesterday using TimeSpan Method
using System;
  
class GFG{
      
static void Main()
{
      
    // Subtract todays date with timespan
    // to find the yesterday date
    DateTime yesterday = DateTime.Now - new TimeSpan(1, 0, 0, 0);
      
    // Find the day, month and year of the yesterday's date
    Console.WriteLine("Yesterday Date: {0}/{1}/{2}",
                      yesterday.Day, yesterday.Month, 
                      yesterday.Year);
}
}


Output:

Yesterday Date: 28/11/2021

Explanation: In the above example, first of all, we find yesterday’s date by subtracting today’s date with the timespan of 1. Here, we get today’s date using the DateTime.Now method. Display yesterday’s date with month, and year in DD/MM/YY format.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 06 Dec, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials