C # how to calculate the time difference?

Source: Internet
Author: User
Tags difference between two times

Tag: OS Io Re C time new

In C #, how to calculate the difference between the two periods. Calculate the difference between two times, which can be calculated to the hour, minute, and second!

<1>
Label1.text = "15:36:05 ";
Label2.text = "20:16:35 ";
Datetime d1 = new datetime );
Datetime D2 = new datetime );

Timespan D3 = d2.subtract (D1 );

Label3.text = "difference :"
+ D3.days. tostring () + "day"
+ D3.hours. tostring () + "hour"
+ D3.minutes. tostring () + "Minute"
+ D3.seconds. tostring () + "seconds ";


<2>
Protected void page_load (Object sender, eventargs E)
{
If (! Ispostback)
{
Datetime dt1 = convert. todatetime ("00:00:00 ");
Datetime dt2 = convert. todatetime ("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 () + "day" + ts. hours. tostring () + "Hour" + ts. minutes. tostring () + "Minute" + 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 time of ST1 is greater than st2, result = 1
If they are equal to 0,
If the value is smaller 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.