Tuesday, September 17, 2013

C# - What is the DateTime Class


The DateTime class is used when you need to review/manipulate any “Date” or “Time” parameter on your application.

Among the abilities for this object:
  • Get the current date of the machine.
  • Manipulate date and time.
  • Get specific date properties (Year - > Month -> Week…).
  • Get specific time properties (Hour - > Minute -> Second…).


To use this class, we first need to create an instance that could be initialized with the class constructor (can be overloaded with 12 different ways…) or initialized with specific properties after declaration. 

Code examples:

Example No'1:
The following code example will demonstrate how to use the DateTime instance with constracur and without.

static void Main(string[] args)
        {
            //Default value for class instance :
            DateTime DefaultValue = new DateTime();
            Console.WriteLine("Default Values: " DefaultValue);

            //initialization using the class Constructor:

            //Creating instance of my birthday time:
            DateTime BirthDay = new DateTime(1984, 5, 31);
            Console.WriteLine("Birthday Date : " + BirthDay);

            //Creating instance with date and time:
            DateTime DateWithSpecificTime = new DateTime(1984, 5, 31, 10, 3, 12);
            Console.WriteLine("Specific Date = " + DateWithSpecificTime);

            //Creating instance based on different calendar:
            TaiwanLunisolarCalendar TaiwanLunisolarCalendar_CalanderCal = new TaiwanLunisolarCalendar();
            DateTime Ta_Calander = new DateTime( 100,6,6,TaiwanLunisolarCalendar_CalanderCal);
            Console.WriteLine("Time Based on different  calendar   = " + Ta_Calander);

        }

Result:
Default Values: 1/1/0001 12:00:00 AM
Birthday Date: 5/31/1984 12:00:00 AM
Specific Date = 5/31/1984 10:03:12 AM
Time Based on different calendar = 7/6/2011 12:00:00 AM

Example No'2:
The next code will demonstrate how to get specific dates based on current day.


static void Main(string[] args)
        {
            DateTime CurrentDay = GetCurrentDay();
            DateTime YesterdayDate = GetYesterdayDate();
            DateTime TomorrowDate = GetTomorrowDate();
            Console.WriteLine("Current Day  = {0}\nYesterday Date = {1}\nTomorrow Date = {2}" ,CurrentDay,YesterdayDate,TomorrowDate);
            Console.ReadKey();
        }

        private static DateTime GetTomorrowDate()
        {
            return DateTime.Today.AddDays(1);
        }

        private static DateTime GetYesterdayDate()
        {
            return DateTime.Today.AddDays(-1);
        }
         
  private static DateTime GetCurrentDay()
        {
            return DateTime.Today;
        }   


Result:
Current Day = 9/14/2013 12:00:00 AM
Yesterday Date = 9/13/2013 12:00:00 AM
Tomorrow Date = 9/15/2013 12:00:00 AM

Example No'3:
The next code will demonstrate how to manipulate specific Date parts.

static void Main(string[] args)
        {
            //Get the current date and time
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Current Time :" + DateTime.Now);
            Console.ResetColor();
            Console.WriteLine();

            //Main methods for Date modifications

            //
            Console.WriteLine("Current Date + 1 Year: " + DateTime.Now.AddYears(1));
            Console.WriteLine("Current Date - 20 Years: " + DateTime.Now.AddYears(-20));
            Console.WriteLine("Current Date + 2 Months: " + DateTime.Now.AddMonths(2));
            Console.WriteLine("Current Date - 2 Months: " + DateTime.Now.AddMonths(-2));
            Console.WriteLine("Current Date + 3 Days: " + DateTime.Now.AddDays(3));
            Console.WriteLine("Current Date - 3 Days: " + DateTime.Now.AddDays(-3));
        }


Result: 











Example No'4:
The next code will demonstrate how to manipulate specific Time parts based on current local time.

static void Main(string[] args)
        {
            //Get the current date and time
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Current Time :" + DateTime.Now);
            Console.ResetColor();
            Console.WriteLine();

            //Main methods for time modifications

            //
            Console.WriteLine("Current Time + 10 Hours: " + DateTime.Now.AddHours(10));
            Console.WriteLine("Current Time - 10 Hours: " + DateTime.Now.AddHours(-10));
            Console.WriteLine("Current Time + 5 Minutes: " + DateTime.Now.AddMinutes(5));
            Console.WriteLine("Current Time - 5 Minutes: " + DateTime.Now.AddMinutes(-5));
            Console.WriteLine("Current Time + 30 Seconds: " + DateTime.Now.AddSeconds(30));
            Console.WriteLine("Current Time - 30 Seconds: " + DateTime.Now.AddSeconds(-30));
        }
    }

Result: 











Example No'5:

The next code will demonstrate how to use specific fields from DateTime instance
        static void Main(string[] args)
        {
            //Get the current date and time
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Current Time :" + DateTime.Now);
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Extract Date: " + DateTime.Now.Date);
            Console.WriteLine("Extract current  year: " + DateTime.Now.Year);
            Console.WriteLine("Extract Day of year: " + DateTime.Now.DayOfYear);
            Console.WriteLine("Extract current month " + DateTime.Now.Month);
            Console.WriteLine("Extract Day(Number): " + DateTime.Now.Day);
            Console.WriteLine("Extract Day of week : " + DateTime.Now.DayOfWeek);
            Console.WriteLine("Extract current hour: " + DateTime.Now.Hour);
            Console.WriteLine("Extract current minute: " + DateTime.Now.Minute);
            Console.WriteLine("Extract current second: " + DateTime.Now.Second);
        }
    }

Result: 














Example No'6:
The next code will demonstrate how to compare different dates by using the “Comparing” method.

Syntax:
The method receives two dates and return an integer that indicates the relations between them.

DateTime.Compare(TheFirstDate, TheSecondDate);

If returned value ‘-‘:  date 1 is older than date 2
If returned value ‘0’: dates are identical
If returned value ‘+’:  date 1 is bigger than date 2

class Program
    {
        static void Main(string[] args)
        {
            DateTime TheFirstDate = new DateTime(2010, 1, 1, 1, 1, 1);
            DateTime TheSecondDate = new DateTime(1900, 2, 2,2, 2, 2);
            DateTime TheThirdDate = new DateTime(1900, 2, 2, 2, 2, 2);
       
           /*
            Available results:
             0 = Identical Dates
             - = TheFirstDate < TheSecondDate
             + = TheFirstDate > TheSecondDate
            */  
             //
          
            //Calling the Comparing method:
           
            CompareDates(TheFirstDate,TheSecondDate);
            CompareDates(TheSecondDate, TheThirdDate);
            CompareDates(TheThirdDate,TheFirstDate);

        }

        private static void CompareDates(DateTime InsertDate1, DateTime insertDate2)
        {
            int Comapring_results = DateTime.Compare(InsertDate1,insertDate2);

            if (Comapring_results == 0 )
            {
               
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Dates Equals");
                Console.ResetColor();
            }
            if (Comapring_results < 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Date1 is smaller than Date2 ");
                Console.ResetColor();
            }
            if (Comapring_results > 0)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Date1 is bigger than Date2 ");
                Console.ResetColor();
            }
        }
    }

Result: 










Example No'7:
The next code will demonstrate how to get days in month by specific year.

class Program
    {
        static void Main(string[] args)
        {
           int [] months = new int [12];
           int year = 2014;
           int ArrayLocation = 0;
           int counter = 1;
           while (counter <= 12)
           {
               months[ArrayLocation] = counter;
               counter++;
               ArrayLocation++;
           }

           foreach (var item in months)
           {
               Console.WriteLine("Totals Days in month {0} : {1}" ,item ,DateTime.DaysInMonth(year, item));
           }
        }

Result: 






My Presentations