Thursday, July 12, 2012

How to Use Time in C# With Example?

Working With Time in C# Example:

We can use TimeSpan Class to work with time in C#. By using this class we can add two times,we can subtract two times. We can format the time according to hours,minutes,seconds and milliseconds.

Example:
class TimeExample
{
static void Main(string[] args)
{
          /*----------Working With Tim e--------------------*/
TimeSpan time1 = new TimeSpan(1,1,30,30); //Parameters are days,hours,mins,secs
Console.WriteLine("Time With Our Values: "+time1);
TimeSpan time2 = new TimeSpan(1, 30, 30); //Parameters are hours,mins,secs
Console.WriteLine("Time With Our Values: " + time2);
           /*-----------Add Two Times----------------*/
TimeSpan span1 =new TimeSpan(2,3,20); //It is 02:03:20 hr:min:sec
TimeSpan span2 = new TimeSpan(5, 3, 20); //It is 05:03:20 hr:min:sec
TimeSpan span3 = span1.Add(span2); //It is 07:06:40
Console.WriteLine("After Adding two Times: "+span3);
}
}

Output: