DateTime class and its methods in C#

Learn: DateTime class and its techniques in C#.net, It’s a predefined class with certain properties and strategies, here we are examining a portion of the normal and well-known techniques for DateTime class.

DateTime is a pre-characterized class of .Net system class library. It is utilized to deal with date and time in our tasks. DateTime class contains a parcel of techniques, that are utilized to perform date and time-related activities.

There are following techniques for DateTime are utilized in C#:

  1. DateTime.DaysInMonth()
  2. DateTime.IsLeapYear()
  3. DateTime.Equals()
  4. DateTime.Compare()
  5. DateTime.Now

1) DateTime.DaysInMonth()

This technique is utilized to get number of days in given month of year.

2) DateTime.IsLeapYear()

This technique is utilized to discover given year is jump year or not.

3) DateTime.Equals()

This technique is utilized to check given dates objects are equivalent or not. This strategy returns Boolean worth.

4) DateTime.Compare()

This technique is utilized to check given dates objects are equivalent or not. This technique returns whole number worth. This strategies returns 0 for equivalent, 1 for first date is more prominent, – 1 for second date is more prominent.

5) DateTime.Now

Here “Now” is property of DateTime class, It return current date and time.

We can comprehend the above techniques with the assistance of the program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int  days = 0       ;
            int  ret  = 0       ;
            bool flag = false   ;
            
            days = DateTime.DaysInMonth(2016, 2);

            Console.WriteLine("Day in Month : "+days);

            flag = DateTime.IsLeapYear(2016);

            if (flag == true)
                Console.WriteLine("\nGiven year is leap year");

            else
                Console.WriteLine("\nGiven year is not leap year");

            Console.WriteLine("Current DateTime :"+ DateTime.Now.ToString());

            DateTime d1 = new DateTime(2017, 6, 10);
            DateTime d2 = new DateTime(2017, 6, 11);

            flag = DateTime.Equals(d1, d2);

            if (flag == true)
                Console.WriteLine("Given dates are equal");
            else
                Console.WriteLine("Given dates are not equal");

            ret = DateTime.Compare(d1, d2);

            if(ret > 0)
                Console.WriteLine("First date is greater");
            else if(ret<0)
                Console.WriteLine("Second date is greater");
            else
                Console.WriteLine("Given dates are equal");

        }
    }
}

Output:

Day in Month : 29
Given year is leap year
Current DateTime :6/8/2017 11:03:54 PM
Given dates are not equal
Second date is greater

Leave a Comment

error: Alert: Content is protected!!