Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以小时:分钟格式显示时间跨度。Ex-(72:59)_C#_Asp.net - Fatal编程技术网

C# 以小时:分钟格式显示时间跨度。Ex-(72:59)

C# 以小时:分钟格式显示时间跨度。Ex-(72:59),c#,asp.net,C#,Asp.net,我编写了这段代码来获取两个日期时间之间的时间跨度: private TimeSpan CalculateTimeDifference() { string StartDate = txtOffBarDate.Text; string StartTime = txtOffbarTime.Text; DateTime StartDateTime = Convert.ToDateTime(StartDate + " " + StartTime); string En

我编写了这段代码来获取两个日期时间之间的时间跨度:

private TimeSpan CalculateTimeDifference()
{
    string StartDate = txtOffBarDate.Text;
    string StartTime = txtOffbarTime.Text;

    DateTime StartDateTime = Convert.ToDateTime(StartDate + " " + StartTime);

    string EndDate = txtOnBarDate.Text;
    string EndTime = txtOnBarTime.Text;

    DateTime EndDateTime = Convert.ToDateTime(EndDate + " " + EndTime);

    TimeSpan TotalTime = StartDateTime.Subtract(EndDateTime);
    return TotalTime ;
}
现在,我想将时间跨度结果存储在00:00格式(小时:分钟)的变量中。请指导我如何操作。

您可以使用和属性:

double hours = TotalTime.TotalHours;
int minutes  = TotalTime.Minutes;
string result = string.Format("{0}:{1}", (int) hours, minutes);

但是,我根本不会使用字符串来存储这些信息。使用
TimeSpan
,因为它包含所有信息,并且仅在需要显示时才将其转换为字符串。

使用TotalHours和ToString()方法,格式为:

如果您的时间跨度少于一天(24小时),请使用以下简单方法:

string result = TotalTime.ToString(@"hh\:mm");
如果没有,请使用以下选项:

string result = string.Format("{0}:{1}", (int)TotalTime.TotalHours, TotalTime.Minutes);
这实际上会返回“00:59”,因为72小时59分钟实际上等于3天0小时59分钟。