私のアプリケーションでは、4 つの TextBox と、開始時刻を入力するための 2 つの TextBox と、終了時刻を入力するための 2 つの TextBox があります。
ユーザーは常に完了時間を入力するため、入力は常に 11:30、12:45 などになります。
開始時刻と終了時刻の時間と分の差を取得するにはどうすればよいですか?
TimeSpan クラスと DateTime の Subtract メソッドを使用します。
DateTime t1 = Convert.ToDateTime(textBox1.Text);
DateTime t2 = Convert.ToDateTime(textBox2.Text);
TimeSpan ts = t1.Subtract(t2);
TimeSpan
引き算で差額を求めることができます。
TimeSpan time1 = TimeSpan.Parse(textBox1.Text);
TimeSpan time2 = TimeSpan.Parse(textBox2.Text);
TimeSpan difference = time1 - time2;
int hours = difference.Hours;
int minutes = difference.Minutes;
create two DateTime
objects parsing the values in the TextBox
controls and simply subtract the two DateTime
, you will get a TimeSpan
object which is what you are looking for.
TimeSpan を使用し、日付を使用する必要はありません
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
タイムスパンを使用:
DateTime dt1 = new DateTime(starttime.text);
DateTime dt2 = new DateTime(endtime.text);
TimeSpan result = dt2 - dt1;
次に、結果から分、秒などを取得できます。
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
2 つの を減算して、構造体DateTime
を受け取ることができます。これには、、、、、などをTimeSpan
取得するためのプロパティがあります。Days
Hours
Minutes
Seconds
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;