Date and Time is one of the important topic in any programming language.
Let us start with the below example.
using System; class MyApplication { public static void Main(string[] arg) { DateTime x = DateTime.Now; System.Console.WriteLine("Current Date and Time is: "+x); } }
Now, if we dissect the output,
So, with the below statement,
DateTime x = DateTime.Now;
We get an object, x that has Year, Month, Day, Hour, Minute and Second.
To use DateTime we need to use the System class,
using System;
So, you got the date in clubbed format. Now, what if you want everything separately.
Well! C# provides that way as well.
using System; class MyApplication { public static void Main(string[] arg) { DateTime x = DateTime.Now; var year = x.Year; var month = x.Month; var day = x.Day; var hour = x.Hour; var minute = x.Minute; var second = x.Second; System.Console.WriteLine("Year : "+year); System.Console.WriteLine("Month : "+month); System.Console.WriteLine("Day : "+day); System.Console.WriteLine("Hour : "+hour); System.Console.WriteLine("Minute : "+minute); System.Console.WriteLine("Second : "+second); } }
Now, if you look at the above output, we have separated the clubbed formatted date.
To display the year, you need to invoke x.Year.
var year = x.Year;
Similar, logic applies for Month, Day, Hour, Minute, Second and Nanosecond.
Now, let us see how to work with Date and Time separately.
To get the date only. Let us look at the below example.
using System; class MyApplication { public static void Main(string[] arg) { DateTime x = DateTime.Today; System.Console.WriteLine("Today's Date is : "+x.ToString("dd-MM-yyyy")); } }
So, with the below statement,
DateTime x = DateTime.Today;
We get an object, x that has the date only i.e. Year, Month, Day.
Similarly, to use DateTime we need to use the System class,
using System;
And if you see the output.
Today's date is 2020-12-10
To get the time only. Let us look at the below example.
using System; class MyApplication { public static void Main(string[] arg) { DateTime x = DateTime.Now; System.Console.WriteLine("Current Time is : "+x.ToString("HH:mm:ss")); } }