w3resource logo
C# Sharp Programming Exercises

C# Sharp Exercises: One year previous and future compare to the current date

C# Sharp DateTime : Exercise-17 with Solution

Write a C# Sharp program to create a date one year previously and the date one year in the future compare to the current date.

Sample Solution:-

C# Sharp Code:

using System;

public class Example17
{
   private enum DateComparisonResult
   {
      Earlier = -1,
      Later = 1,
      TheSame = 0
   };

   public static void Main()
   {
      DateTime thisDate = DateTime.Today;


      DateTime thisDateNextYear, thisDateLastYear;

      //  add/substract 1 year
      thisDateNextYear = thisDate.AddYears(1);
      thisDateLastYear = thisDate.AddYears(-1);   

      DateComparisonResult comparison;
      // Compare today to last year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateLastYear);
      Console.WriteLine("{0}: {1:d} is {2} than {3:d}", 
                        (int) comparison, thisDate, comparison.ToString().ToLower(), 
                        thisDateLastYear);

      // Compare today to next year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateNextYear);
      Console.WriteLine("{0}: {1:d} is {2} than {3:d}", 
                        (int) comparison, thisDate, comparison.ToString().ToLower(), 
                        thisDateNextYear);
   }
}

Sample Output:

1: 6/10/2017 is later than 6/10/2016                                                                          
-1: 6/10/2017 is earlier than 6/10/2018   

C# Sharp Code Editor:

using System;

public class Example17
{
   private enum DateComparisonResult
   {
      Earlier = -1,
      Later = 1,
      TheSame = 0
   };

   public static void Main()
   {
      DateTime thisDate = DateTime.Today;


      DateTime thisDateNextYear, thisDateLastYear;

      //  add/substract 1 year
      thisDateNextYear = thisDate.AddYears(1);
      thisDateLastYear = thisDate.AddYears(-1);   

      DateComparisonResult comparison;
      // Compare today to last year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateLastYear);
      Console.WriteLine("{0}: {1:d} is {2} than {3:d}", 
                        (int) comparison, thisDate, comparison.ToString().ToLower(), 
                        thisDateLastYear);

      // Compare today to next year
      comparison = (DateComparisonResult) thisDate.CompareTo(thisDateNextYear);
      Console.WriteLine("{0}: {1:d} is {2} than {3:d}", 
                        (int) comparison, thisDate, comparison.ToString().ToLower(), 
                        thisDateNextYear);
   }
}

Improve this sample solution and post your code through Disqus