Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - DATE & TIME


Date and Time is one of the important topic in any programming language.


Let us start with the below example.


Example :



using System;

class MyApplication
{
    public static void Main(string[] arg) 
    {
    	DateTime x = DateTime.Now;
        System.Console.WriteLine("Current Date and Time is: "+x);
    }
} 


Output :



  Current Date and Time is: 03/16/2022 15:09:24

Now, if we dissect the output,

C_Sharp

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.


Example :



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);
    }
} 


Output :



  Year : 2021
  Month : 3
  Day : 16
  Hour : 15
  Minute : 19
  Second : 28

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.


Working with Dates


To get the date only. Let us look at the below example.


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"));
    }
} 


Output :



  Today's Date is : 16-03-2021

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

Working with Time


To get the time only. Let us look at the below example.


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"));
    }
} 


Output :



  Current Time is : 16:29:16