How to calculate the difference between two times in C #. Calculate the difference between 2 times, you can calculate the time seconds!
The code is as follows |
Copy Code |
<1> Label1. Text = "2004-1-1 15:36:05″; Label2. Text = "2004-3-1 20:16:35″; DateTime d1 =new datetime (2004,1,1,15,36,05); DateTime d2 =new datetime (2004,3,1,20,16,35); TimeSpan D3 = D2. Subtract (D1); Label3. Text = "Difference:" +d3. Days.tostring () + "Days" +d3. Hours.tostring () + "hours" +d3. Minutes.tostring () + "minutes" +d3. Seconds.tostring () + "seconds"; <2> protected void Page_Load (object sender, EventArgs e) { if (! IsPostBack) { DateTime dt1 = Convert.todatetime ("2009-07-31 00:00:00″"); DateTime DT2 = Convert.todatetime ("2009-08-02 00:00:00″"); This. Label1.Text = this. DateDiff (DT1,DT2); } } private String DateDiff (DateTime DateTime1, datetime DateTime2) { string dateDiff = null; Try { TimeSpan ts1 = new TimeSpan (datetime1.ticks); TimeSpan ts2 = new TimeSpan (datetime2.ticks); TimeSpan ts = ts1. Subtract (TS2). Duration (); DateDiff = ts. Days.tostring () + "days" + TS. Hours.tostring () + "hour" + TS. Minutes.tostring () + "minutes" + TS. Seconds.tostring () + "seconds"; } Catch { } return DateDiff; } <3> String st1 = "14:16″;" String st2 = "14:14″;" DateTime dt1 = Convert.todatetime (ST1); DateTime DT2 = Convert.todatetime (ST2); int result = Datetime.compare (DT1, DT2); |
If the st1 time is greater than st2 , result = 1
If equal equals 0,
if less than-1