Getting different parts of date and time using DateTime structure in C#

In the previous tutorial you learnt how to display the date and time in long and short formats. In this tutorial we will dissect the date and time part of the DateTime information and get the day, month ,year, hour, minutes, seconds components from it. All this information is available as integer values and can be used for doing different types of comparisons in your application.

Getting the day, month and year information

Look at the code below

class Program  {      static void Main(string[] args)      {          Console.WriteLine("Today is {0}st day of the {1}th month" ,DateTime.Today.Day, DateTime.Today.Month);          Console.WriteLine("The current year is : " + DateTime.Today.Year);        }  }

In this code we are displaying the day number and month using the DateTime.Today.Day and DateTime.Today.Month properties. In the second line we are displaying the current year by using the DateTime.Today.Year property. The output of the code is as shown below

Day, month and year information from DateTime in C#
Getting hours, minutes and seconds information

Similar to what we have done with the date information above we can also get different parts of the time information like hours, minutes and seconds from the DateTime structure. Look at the code below

class Program  {      static void Main(string[] args)      {          Console.WriteLine("Current time is ");          Console.WriteLine("{0} hours", DateTime.Now.Hour);          Console.WriteLine("{0} minutes",DateTime.Now.Minute);          Console.WriteLine("And {0} seconds of the day",DateTime.Now.Second);      }  }

In this code we are getting the Hour, Minute and Second information from the Now property of the DateTime structure. The output of this code is as shown below

Hours, minutes and seconds information from DateTime in C#

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp