This program creates two DateTime
objects, date1
and date2
, that represent two specific dates. It then calls the Compare
method of the DateTime
struct to compare the two dates. The Compare
method returns a negative value if the first date is earlier than the second date, a positive value if the first date is later than the second date, and 0 if the two dates are the same.
The program uses an if statement to check the value of the result
variable and print a message to the console indicating which date is earlier or whether the dates are the same. The output of this program will be “5/1/2022 is earlier than 10/1/2022”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | using System; class Program { static void Main() { DateTime date1 = new DateTime(2022, 5, 1); DateTime date2 = new DateTime(2022, 10, 1); int result = DateTime.Compare(date1, date2); if (result < 0) { Console.WriteLine("{0} is earlier than {1}", date1, date2); } else if (result == 0) { Console.WriteLine("{0} is the same as {1}", date1, date2); } else { Console.WriteLine("{0} is later than {1}", date1, date2); } } } |