Gigi Labs

Please follow Gigi Labs for the latest articles. Programmer's Ranch no longer has its domain, so please update your bookmarks and links to programmersranch.blogspot.com.

Sunday, May 5, 2013

C# Basics: Calculating Pension Age with DateTime and if's

Hello everyone! :)

In my recent article, C# Basics: Fun with Integers, we wrote a little program that tells you how many years you have left until you get your beloved pension. Because that's what people do when they love their job, right? Right?

Well, that example was a little bit oversimplified. As my friend Chris Tanti pointed out, here in Malta, you don't just retire at 65. To be more precise, "if you were born:
  • on the 31st December 1951 or before, your retirement age is 60 years if female and 61 years if male 
  • between 1952 and 1955, your retirement age is 62 years 
  • between 1956 and 1958, your retirement age is 63 years 
  • between 1959 and 1961, your retirement age is 64 years 
  • on the 1st January 1962 or after, your retirement age is 65 years"

This is just slightly more complicated than we did last time. In this article, we're going to learn about the DateTime data type, and how to use if statements, among other things.

Create a new console application, and throw out the sample code that is generated by SharpDevelop. Let's start with this short piece of code:

            Console.WriteLine("Enter your date of birth...");
            String dateAsString = Console.ReadLine();
            DateTime dateOfBirth = Convert.ToDateTime(dateAsString);
           
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

So, the only thing that's new here is the third line. You might remember from C# Basics: Fun with Integers that we had used Convert.ToInt32() to convert from a String to an int. Well, it turns out that you can convert from just about any data type to just about any other data type, so what we're doing here is converting from a String to a DateTime. Then we store the result in an appropriately declared variable of type DateTime.

So what is this DateTime thing? As the name implies, it stores both date and time (you can use just one or the other only, if you wish). In our case we're getting the user's date of birth, so we don't really care about the time. In order for the conversion to work, the date entered by the user must be in a recognised format. One way to do this is to write the date such that the year comes first, e.g. 15th August 1987 becomes 1987-08-15. This format is called ISO8601.


Once we have a DateTime, it is easy to work with the day, month, year, etc. We obtain the year of birth simply by doing this:

             int yearOfBirth = dateOfBirth.Year;

We are now in a position to find out when the user retires. We first declare a variable where we will store the retirement age, to later show it to the user:

             int pensionAge = 0;

Next, we start writing the conditions. Let's assume the user is female to keep things simple. Therefore:

             if (yearOfBirth < 1952)
            {
                pensionAge = 60;
            }

This is our first example of a conditional statement. It works like this: if the condition in the brackets is true, then execute the stuff in the curly brackets. In this case, if the year of birth is less than 1952, we set the pension age to 60.

Here are all the conditions put together (note: if you only have single statements, as in this case, you can actually leave out the curly brackets):

             if (yearOfBirth < 1952)
            {
                pensionAge = 60;
            }
            else if (yearOfBirth >= 1952 && yearOfBirth <= 1955)
            {
                pensionAge = 62;
            }
            else if (yearOfBirth >= 1956 && yearOfBirth <= 1958)
            {
                pensionAge = 63;
            }
            else if (yearOfBirth >= 1959 && yearOfBirth <= 1961)
            {
                pensionAge = 64;
            }
            else
            {
                pensionAge = 65;
            }

In this case we use else if instead of just an if for subsequent conditions, and then finish off with an else that handles all other conditions that don't fall under any of the previous ones. In this case, the else caters for cases where yearOfBirth is greater than 1962.

The else if conditions are slightly more complex than the first if. This is because they actually have two conditions, joined by an AND (&&) operator. <= and >= mean less than or equal, and greater than or equal, respectively. So if yearOfBirth is greater than or equal to 1952, AND less than or equal to 1955, the condition is true, and pensionAge is set to 62. Just one condition isn't enough to make it true.

Okay, so now we know at what age the user is retiring. We just need to tell her how many years away she is! We can get the date and time right now from the computer by using:

            DateTime now = DateTime.Now;

Then, as before, we can get the year from that:

            int currentYear = now.Year;

So we calculate how many years are left:

            int yearsLeft = yearOfBirth + pensionAge - currentYear;

...and then display it to the user:

            Console.WriteLine("You retire at {0}, that means {1} years left!", pensionAge, yearsLeft);


One last thing. You'll notice that in this Console.WriteLine() we are not just using {0} as we did before - we now have a {1}! As a matter of fact, you can put as many parameters as you like in Console.WriteLine(), and then refer to them in the String according to their order ({0}, {1}, {2}, {3}, etc). In this case {0} refers to pensionAge, and {1} refers to yearsLeft.

Wonderful! This wraps up today's article, in which we learned about the DateTime data type, how to use conditions, how to include multiple variables in Console.WriteLine(), and also the sad truth that pension is still far, far away! :) Until next time, folks!

No comments:

Post a Comment