本文主要是介绍C#计算两个时间之间的时差,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C#计算两个时间之间的时差就例如SQL中的DATEADD的功能
public string GetDateAddIf(string oldtime, string newtime)
{
DateTime old1 = Convert.ToDateTime(oldtime);
DateTime new1 = Convert.ToDateTime(newtime);
int h1 = Convert.ToInt32(old1.Hour);
int h2 = Convert.ToInt32(new1.Hour);
int minite1 = Convert.ToInt32(old1.Minute);
int minite2 = Convert.ToInt32(new1.Minute);
int second1 = Convert.ToInt32(old1.Second);
int second2 = Convert.ToInt32(new1.Second);
int h = 0;
int minite = 0;
int second = 0;
h = h2 - h1;
if (minite2 < minite1)
{
minite = 60 - minite1 + minite2;
h = h - 1;
}
if (minite2 > minite1)
{
minite = minite2 - minite1;
}
if (second2 > second1)
{
second =second2 - second1;
}
if (second2 < second1)
{
second = 60-second1 +second2;
if(!minite.Equals(0))
minite = minite - 1;
}
return h.ToString() + "小时" + minite.ToString() + "分钟" + second.ToString() + "秒";
}
例如: public string datetime = DateTime.Now.ToString();
private void timer1_Tick(object sender, EventArgs e)
{
ltcontrol.ltcontrol mm = new ltcontrol.ltcontrol();
label1.Text=mm.GetDateAddIf(datetime, DateTime.Now.ToString());
}
这篇关于C#计算两个时间之间的时差的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!