Advertisement
sylviapsh

Read Two Dates And Calculate The Period Between Them

Jan 30th, 2013
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using System;
  2. using System.Globalization;
  3.  
  4. class ReadTwoDatesCalcPeriodBetweenThem
  5. {
  6.   //Write a program that reads two dates in the format: day.month.year and calculates the number of days between them. Example:
  7.   //Enter the first date: 27.02.2006
  8.   //Enter the second date: 3.03.2006
  9.   //Distance: 4 days
  10.  
  11.   static DateTime ParseDate(string dateAsString)
  12.   {
  13.     DateTime date = DateTime.ParseExact(dateAsString, "d.M.yyyy", CultureInfo.InvariantCulture);
  14.     return date;
  15.   }
  16.  
  17.   static void Main()
  18.   {
  19.     Console.WriteLine("The format for the dates is day.month.year (e.g. 31.12.2012)");
  20.  
  21.     try
  22.     {
  23.       Console.Write("Enter the first date: ");
  24.       string input = Console.ReadLine();
  25.       DateTime startDate = ParseDate(input);
  26.  
  27.       Console.Write("Enter the second date: ");
  28.       input = Console.ReadLine();
  29.       DateTime endDate = ParseDate(input);
  30.  
  31.       double resultDistance = (endDate - startDate).TotalDays;
  32.  
  33.       Console.WriteLine("Distance: {0} day/s/", resultDistance);
  34.     }
  35.     catch (FormatException)
  36.     {
  37.       Console.WriteLine("Please enter the dates in the correct format 31.12.2012! Make sure that such a date exists!"); ;
  38.     }
  39.     catch (ArgumentNullException)
  40.     {
  41.       Console.WriteLine("Please provide a date. The date cannot be null!");
  42.     }
  43.   }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement