已知设备已运行时间【比如:时间间隔12345678秒】,计算出已运行dd天HH时mm分ss秒
新建C#窗体应用程序CalculateTimespanDemo,输入一个时间间隔,计算出耗时
窗体设计如图:
主要的两个方法:
private string GetTimespanDescription(int timespanSecond);
private string GetTimespanDescriptionRecursion(int timespanSecond);
窗体FormCalculateTimespan源程序如下
(忽略设计器自动生成的代码):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CalculateTimespanDemo
{
public partial class FormCalculateTimespan : Form
{
public FormCalculateTimespan()
{
InitializeComponent();
txtDescription.ReadOnly = true;
}
/// <summary>
/// 获得指定时间间隔(秒)的描述
/// </summary>
/// <param name="timespanSecond"></param>
/// <returns></returns>
private string GetTimespanDescription(int timespanSecond)
{
//一天为24小时,一小时3600秒,一天为86400秒
if (timespanSecond <= 0)
{
return "0秒";
}
if (timespanSecond < 60)
{
return $"{timespanSecond}秒";
}
if (timespanSecond < 3600)
{
return $"{timespanSecond / 60}分{timespanSecond % 60}秒";
}
if (timespanSecond < 86400)
{
return $"{timespanSecond / 3600}时{timespanSecond % 3600 / 60}分{timespanSecond % 3600 % 60}秒";
}
int days = timespanSecond / 86400;
int remainder = timespanSecond - days * 86400;
return $"{days}天{remainder / 3600}时{remainder % 3600 / 60}分{remainder % 3600 % 60}秒";
}
/// <summary>
/// 获得指定时间间隔(秒)的描述,使用递归
/// </summary>
/// <param name="timespanSecond"></param>
/// <returns></returns>
private string GetTimespanDescriptionRecursion(int timespanSecond)
{
//一天为24小时,一小时3600秒,一天为86400秒
if (timespanSecond <= 0)
{
return "0秒";
}
if (timespanSecond < 60)
{
return $"{timespanSecond}秒";
}
if (timespanSecond < 3600)
{
return $"{timespanSecond / 60}分{GetTimespanDescriptionRecursion(timespanSecond % 60)}";
}
if (timespanSecond < 86400)
{
return $"{timespanSecond / 3600}时{GetTimespanDescriptionRecursion(timespanSecond % 3600)}";
}
int days = timespanSecond / 86400;
int remainder = timespanSecond - days * 86400;
return $"{days}天{GetTimespanDescriptionRecursion(remainder)}";
}
/// <summary>
/// 校验输入并显示反馈结果
/// </summary>
/// <param name="timespanSecond"></param>
/// <returns></returns>
private bool CheckInput(out int timespanSecond)
{
if (!int.TryParse(txtTimespan.Text, out timespanSecond))
{
txtTimespan.Focus();
MessageBox.Show("请输入整数", "出错");
return false;
}
if (timespanSecond < 0)
{
txtTimespan.Focus();
MessageBox.Show("请输入自然数【不能为负数】", "出错");
return false;
}
return true;
}
/// <summary>
/// 显示描述结果
/// </summary>
/// <param name="func"></param>
private void DisplayResult(Func<int, string> func)
{
if (!CheckInput(out int timespanSecond))
{
return;
}
string timeDescription = func(timespanSecond);
txtDescription.Text = timeDescription;
}
private void bntCalculate_Click(object sender, EventArgs e)
{
DisplayResult(GetTimespanDescription);
}
private void btnRecursion_Click(object sender, EventArgs e)
{
DisplayResult(GetTimespanDescriptionRecursion);
}
}
}
窗体运行如图: