Example of C # calculation time lag in asp.net

Source: Internet
Author: User
Tags datetime difference between two times


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.