获得两个时间之间的时间跨度在C#中? [英] Getting time span between two times in C#?

查看:124
本文介绍了获得两个时间之间的时间跨度在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本框。一个在时间的时钟,一个用于时钟输出。本次将放在格式为:

 小时:分钟

可以说,我已经在上午7:00在主频和下午2:00同步输出。

使用我目前的code,我得到2小时的区别,但它应该是7小时。我会怎么做,在C#。我要转换为24小时,通过让用户选择上午或下午,但我糊涂了。

所以,基本上,我将如何计算的小时两个时间之间的区别?

我想这一点,但得到了2小时,没有7,当我在这些数字插入。

 日期时间STARTTIME = Convert.ToDateTime(textBox1.Text);
日期时间ENDTIME = Convert.ToDateTime(textBox2.Text);时间跨度持续时间=的startTime - 结束时间;


解决方案

 字符串STARTTIME =7:00 AM;
字符串ENDTIME =2:00 PM时间跨度持续时间= DateTime.Parse(结束时间).Subtract(DateTime.Parse(startTime时));Console.WriteLine(持续时间);
Console.ReadKey();

将输出:07:00:00

它也可以,如果用户输入军用时间:

 字符串STARTTIME =7:00;
字符串ENDTIME =14:00;时间跨度持续时间= DateTime.Parse(结束时间).Subtract(DateTime.Parse(startTime时));Console.WriteLine(持续时间);
Console.ReadKey();

输出:07:00:00

要更改格式为: duration.ToString(@HH \\:MM)

更多信息,时间:的<一个href=\"http://msdn.microsoft.com/en-us/library/ee372287.aspx\">http://msdn.microsoft.com/en-us/library/ee372287.aspx

I have two textboxes. One for a clock in time and one for clock out. The times will be put in this format:

Hours:Minutes

Lets say I have clocked in at 7:00 AM and clocked out at 2:00 PM.

With my current code, I get a difference of 2 hours, but it should be 7 hours. How would I do that in C#. I was going to convert to the 24 hour, by letting the user select AM or PM, but I got confused.

So, basically, how would I calculate the difference of hours between the two times?

I tried this, but got 2 hours and not 7 when I plugged in the numbers.

DateTime startTime = Convert.ToDateTime(textBox1.Text);
DateTime endtime = Convert.ToDateTime(textBox2.Text);

TimeSpan duration = startTime - endtime;

解决方案

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

这篇关于获得两个时间之间的时间跨度在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆