w3resource

C#: 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 one year in the future compared to the current date.

Sample Solution:-

C# Sharp Code:

using System;

public class Example17
{
    // Enum to represent different date comparison results
    private enum DateComparisonResult
    {
        Earlier = -1,
        Later = 1,
        TheSame = 0
    };

    // Main method, entry point of the program
    public static void Main()
    {
        // Get the current date
        DateTime thisDate = DateTime.Today;

        // Declare variables to hold dates for next and last year
        DateTime thisDateNextYear, thisDateLastYear;

        // Add/subtract 1 year to the current date
        thisDateNextYear = thisDate.AddYears(1);
        thisDateLastYear = thisDate.AddYears(-1);

        DateComparisonResult comparison; // Declare a variable of DateComparisonResult type

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

        // Compare today's date to next year's date
        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   

Flowchart:

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

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program that compares two dates.
Next: Write a C# Sharp program to compare the current date with a given date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.