简体   繁体   中英

Getting time difference between two values

In my application I have 4 TextBoxes, and 2 TextBoxes to enter the start-time, and 2 TextBoxes to enter end-time.

The user will always enter a completed time, so the input will always be 11:30, 12:45, and so on.

How can I get the difference in hours and minutes between start and endtime?

Use TimeSpan class, and Subtract method of DateTime.

        DateTime t1 = Convert.ToDateTime(textBox1.Text);
        DateTime t2 = Convert.ToDateTime(textBox2.Text);
        TimeSpan ts = t1.Subtract(t2);

You can get a TimeSpan of the difference by subtractraction.

TimeSpan time1 = TimeSpan.Parse(textBox1.Text);
TimeSpan time2 = TimeSpan.Parse(textBox2.Text);

TimeSpan difference = time1 - time2;

int hours = difference.Hours;
int minutes = difference.Minutes;

创建两个DateTime对象解析TextBox控件中的值,然后简单地减去两个DateTime ,您将获得一个TimeSpan对象,这是您正在寻找的。

use TimeSpan, no need to use dates

var start = TimeSpan.Parse(start.Text);
var end = TimeSpan.Parse(end.Text);

TimeSpan result = end - start;
var diffInMinutes = result.TotalMinutes();
TimeSpan difference = DateTime.Parse(txtbox1.Text) - Datetime.Parse(txtbox2.Text);

Example:

TimeSpan difference =  DateTime.Parse("12:55")-DateTime.Parse("11:45");
double hourDiff=  difference.TotalHours;
double minutes = difference.TotalMinutes;
Console.WriteLine(hourDiff);//1.16666666666667
Console.WriteLine(minutes);//70

Use timespan :

    DateTime dt1 = new DateTime(starttime.text);
    DateTime dt2 = new DateTime(endtime.text);

    TimeSpan result = dt2 - dt1;

Then you can get the minutes, seconds etc from result.

convert the hours to minutes, add it to the existing minutes, convert those down to total seconds, do the same with endtime. minus them from each other, convert them back up to hours and minutes. remembering 60 minutes in an hour, 60 seconds in a minute, thats how i would deal with it. because total seconds will always be the same, its hard trying to teach a computer trying to wrap around from 60 back to 0 or from 12 to 1. much easier to use somethign perfectly linear like seconds. then reconvert upwards

You can subtract two DateTime s and receive a TimeSpan structure. This has properties for retrieving Days , Hours , Minutes , Seconds , etc.

var first = new DateTime(2012, 05, 08, 10, 30, 00);
var second = new DateTime(2012, 05, 08, 11, 49, 13);

var diff = first - second;
var hours = diff.Hours;
var mins = diff.Minutes;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM