Advertisement
dimipan80

Advanced Topics 4. Difference between Dates

Jul 1st, 2014
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. // Write a program that enters two dates in format dd.MM.yyyy and returns the number of days between them.
  2.  
  3. namespace _04.DifferenceBetweenDates
  4. {
  5.     using System;
  6.     using System.Globalization;
  7.     using System.Threading;
  8.  
  9.     public class DifferenceBetweenDates
  10.     {
  11.         public static void Main(string[] args)
  12.         {
  13.             checked
  14.             {
  15.                 Console.WriteLine("The Date must enters exactly like this format [dd.MM.yyyy] !");
  16.                 Console.Write("Enter the First date: ");                
  17.                 DateTime firstDate = ReadStringFromInputAndConvertToDateTimeFormat();
  18.                 Console.Write("Enter the Second date: ");
  19.                 DateTime secondDate = ReadStringFromInputAndConvertToDateTimeFormat();
  20.                 int daysBetweenDates = CalculateDaysBetweenTwoDates(firstDate, secondDate);
  21.                 Console.WriteLine("Days Between these two Dates are: {0} !", daysBetweenDates);
  22.             }
  23.         }
  24.  
  25.         private static int CalculateDaysBetweenTwoDates(DateTime firstDate, DateTime secondDate)
  26.         {
  27.             checked
  28.             {
  29.                 TimeSpan diff = secondDate - firstDate;
  30.                 int days = diff.Days;
  31.                 return days;
  32.             }
  33.         }
  34.  
  35.         private static DateTime ReadStringFromInputAndConvertToDateTimeFormat()
  36.         {
  37.             checked
  38.             {
  39.                 string inputStr = Console.ReadLine();
  40.                 string dateTimeFormatStr = "d.MM.yyyy";
  41.                 DateTime date = DateTime.ParseExact(inputStr, dateTimeFormatStr, CultureInfo.InvariantCulture);
  42.                 return date;
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement