Wednesday, 27 June 2012

.Net Tips : Get Time Span between two dates using TimeSpan Class

In .NET Framework 4 there is enhancement in TimeSpan Class, These include new overloads of the ToString , TryParse and Parse methods, and also introduce new methods like TryParseExact  and ParseExact.
Using time span class you get time span interval between two dates, this timespan gets in days , hour , minute , seconds and milliseconds format. .Net Beginners very much like this type of example.

Here is example of this.
In this example we take Departure and Arrival dates and we get total travel time span.

C# Example :
 DateTime objDepartureDt = new DateTime(2012, 6, 1, 5, 42, 0);
 DateTime objArrivalDt = new DateTime(2012, 6, 2, 11, 17, 0);
 TimeSpan objTravelTimeTS = objArrivalDt - objDepartureDt;

 Response.Write(string.Format("<b>TimeSpan :</b> {0} - {1} = <b> {2} </b>", objArrivalDt, objDepartureDt, objTravelTimeTS));

 Response.Write("<br/><br/>");
 Response.Write("<b>Interval details</b>");
 Response.Write("<br/>Days : " + objTravelTimeTS.Days);
 Response.Write("<br/>Hours : " + objTravelTimeTS.Hours);
 Response.Write("<br/>Minutes : " + objTravelTimeTS.Minutes);
 Response.Write("<br/>Second : " + objTravelTimeTS.Seconds);
 Response.Write("<br/>Milliseconds : " + objTravelTimeTS.Milliseconds);

VB.net Example :
 Dim objDepartureDt As New DateTime(2012, 6, 1, 5, 42, 0)
 Dim objArrivalDt As New DateTime(2012, 6, 2, 11, 17, 0)
 Dim objTravelTimeTS As TimeSpan = objArrivalDt - objDepartureDt

 Response.Write(String.Format("<b>TimeSpan :</b> {0} - {1} = <b> {2} </b>", objArrivalDt, objDepartureDt, objTravelTimeTS))

 Response.Write("<br/><br/>")
 Response.Write("<b>Interval details</b>")
 Response.Write("<br/>Days : " & objTravelTimeTS.Days)
 Response.Write("<br/>Hours : " & objTravelTimeTS.Hours)
 Response.Write("<br/>Minutes : " & objTravelTimeTS.Minutes)
 Response.Write("<br/>Second : " & objTravelTimeTS.Seconds)
 Response.Write("<br/>Milliseconds : " & objTravelTimeTS.Milliseconds)

Output : 



There are also a properties like TotalDays, TotalHours, TotalMinutes, TotalSeconds and TotalMilliseconds. Using these properties you can get time span in specific values.

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment