w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Compare the current date with a given date

Secondary Nav

C# Sharp DateTime : Exercise-18 with Solution

Write a C# Sharp program to compare the current date with a given date.

Expected Output :

7/28/2016 is in the past.

C# Sharp Code:

using System;

public class Example18
{
   public static void Main()
   {
      System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28);
int compareValue;

try 
{
    compareValue = theDay.CompareTo(DateTime.Today);
} 
catch (ArgumentException) 
{
   Console.WriteLine("Value is not a DateTime");
   return;
}

if (compareValue < 0) 
   System.Console.WriteLine("{0:d} is in the past.", theDay);
else if (compareValue == 0) 
   System.Console.WriteLine("{0:d} is today!", theDay);
else // compareValue > 0
   System.Console.WriteLine("{0:d} has not come yet.", theDay);
   }
}

C# Sharp Practice online:

using System;

public class Example18
{
   public static void Main()
   {
      System.DateTime theDay = new System.DateTime(System.DateTime.Today.Year, 7, 28);
int compareValue;

try 
{
    compareValue = theDay.CompareTo(DateTime.Today);
} 
catch (ArgumentException) 
{
   Console.WriteLine("Value is not a DateTime");
   return;
}

if (compareValue < 0) 
   System.Console.WriteLine("{0:d} is in the past.", theDay);
else if (compareValue == 0) 
   System.Console.WriteLine("{0:d} is today!", theDay);
else // compareValue > 0
   System.Console.WriteLine("{0:d} has not come yet.", theDay);
   }
}

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:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number