Banner

Console Date Diff

C#

/*
    Written by: Michael Eaton
    Date: Mon Apr 15 2002
    Simple way to get the difference (in days) between two
    dates.
*/

using System;

class DateDiff {
    public static void Main(string[] args) {

        DateTime StartDate = new DateTime();
        DateTime EndDate = new DateTime();
        String DiffBy = "";
        TimeSpan Diff = new TimeSpan();

        if (args.Length != 2) {
            Usage();
            return;
        } else {
            try {
                if (args[0] != "") {
                    StartDate = DateTime.Parse(args[0]);
                }
                if (args[1] != "") {
                    EndDate = DateTime.Parse(args[1]);
                }
                if (args[2] !="") {
                    DiffBy = args[2];
                }
                Diff = EndDate.Subtract(StartDate);
                Console.WriteLine("The number of days between '{0}' and '{1}' is {2}.",
                StartDate.ToShortDateString(), EndDate.ToShortDateString(), Diff.Days);
            } catch (FormatException) {
                Console.WriteLine("Please enter valid dates.");
            } catch (Exception e) {
                Console.WriteLine("An exception has occurred: {0}.", e);
            }
        }
    }

    private static void Usage() {
        Console.WriteLine("Mike's Command-Line DateDiff printer");
        Console.WriteLine("Displays the number of days between two dates");
        Console.WriteLine("(C) Copyright 2002 Michael Eaton\n");
        Console.WriteLine("Usage: DateDiff <startdate> <enddate>");
        Console.WriteLine();
        Console.WriteLine("Start date and End date must be valid dates.");
    }
}
csharpindex.com/colorCode
Save as 'datediff.cs'.
Compile at the command-line using: 'csc datediff.cs'
Back to the samples...