w3resource logo


C# Sharp Programming Exercises

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

Secondary Nav

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.

Expected Output :

 1: 8/20/2016 is later than 8/20/2015                                             
-1: 8/20/2016 is earlier than 8/20/2017                       

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);
   }
}

C# Sharp Practice online:

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.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program