Fun with DateTime

The results of my messing around with .NET DateTime. Hope this is useful for someone else!

using System;
namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
      // fun with DateTime
      // right now, including the time
      Console.WriteLine(DateTime.Now);

      // today's date, no time (midnite)
      Console.WriteLine(DateTime.Today);

      // stripping a time off a DateTime (so it's midnite, useful for database queries)
      DateTime startDate = DateTime.Parse("10/31/2008 5:25 pm"); // pretend this came from a database or something
      Console.WriteLine(startDate); // see the time displayed
      startDate = startDate.Date; // this is just the date portion with no time
      Console.WriteLine(startDate); // see, just has the date now

      // difference, in number of days, between two dates, human-logic, that is, the 5th is 2 days after the 3rd, no matter what time it was
      DateTime endDate = DateTime.Parse("11/03/2008 4:25 pm"); // pretend this came from a database or something, too
      int days = (startDate.Date - endDate.Date).Duration().Days; // absolute value, order of start and end dates is not important
      Console.WriteLine(days);
      int days2 = (startDate.Date - endDate.Date).Days; // real value, order of start and end dates IS important
      Console.WriteLine(days2);

      // difference between dates with time portion, such as .25 hours (time and attendance, payroll)
      startDate = DateTime.Parse("11/17/2008 8:00 am");
      endDate = DateTime.Parse("11/17/2008 4:45 pm");
      TimeSpan interval = endDate - startDate; // order matters
      Console.WriteLine(interval);

      // hey, don't we get a lunch break?
      DateTime startLunch = DateTime.Parse("11/17/2008 12:00 pm");
      DateTime endLunch = DateTime.Parse("11/17/2008 12:25 pm");
      TimeSpan lunchInterval = endLunch - startLunch; 
      Console.WriteLine(interval - lunchInterval); // 20 minutes of overtime! (yeah, right)

      Console.Read();
      }
   }
}

Leave a Reply