Home »
.Net
DateTime class and its methods in C#
Learn: DateTime class and its methods in C#.net, It’s a predefined class with some properties and methods, here we are discussing some of the common and popular methods of DateTime class.
DateTime is a pre-defined class of .Net framework class library. It is used to handle date and time in our projects. DateTime class contains lot of methods, that are used to perform date and time related operations.
There are following methods of DateTime are used in C#:
- DateTime.DaysInMonth()
- DateTime.IsLeapYear()
- DateTime.Equals()
- DateTime.Compare()
- DateTime.Now
1) DateTime.DaysInMonth()
This method is used to get number of days in given month of year.
2) DateTime.IsLeapYear()
This method is used to find given year is leap year or not.
3) DateTime.Equals()
This method is used to check given dates objects are equal or not. This method returns Boolean value.
4) DateTime.Compare()
This method is used to check given dates objects are equal or not. This method returns integer value. This methods returns 0 for equal, 1 for first date is greater, -1 for second date is greater.
5) DateTime.Now
Here "Now" is property of DateTime class, It return current date and time.
We can understand above methods with the help of 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");
}
}
}
After compiling above program we got following result
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