c# - C# - 如何从gridview计算时间hh:mm

我曾经使用下面的代码来汇总GridView中一列的总数,并将它用作分钟数:


int total = 0;


 protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)


 {


 if (e.Row.RowType == DataControlRowType.DataRow)


 {


 total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));


 }


 }



列数据只是数字,例如:

 
2


33


50


120



 

但是,检索该列的数据的数据类型为nvarchar (hh:mm ),并希望将它求和,例如:


01:30


00:45


00:05


02:00



要成为:

 
04:20



 
时间:

您可以使用TimeSpan.FromMinutes(minutesInDouble),以double格式传递上述值。

阅读此文章

你可以使用System.TimeSpan以时间格式获取结果


TimeSpan total = new TimeSpan();



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)


{


 if (e.Row.RowType == DataControlRowType.DataRow)


 {



 var ts = DataBinder.Eval(e.Row.DataItem, "Amount").ToString(); 


 var t = DateTime.Parse(ts).TimeOfDay;


 totalTime += t;


 }



你可以尝试以下操作:


static void Main(string[] args)


{


 string hours = @"


 01:30


 00:45


 00:05


 02:00";



 TimeSpan totalHoursSpan = hours.Split(new [] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)


 .Select(x => DateTime.ParseExact(x.Trim(), "HH:mm", CultureInfo.InvariantCulture).TimeOfDay)


 .Aggregate(TimeSpan.Zero, (total, span) => total += span);



 string totalHrs = string.Format("{0:00}:{1:00}", (int)totalHoursSpan.TotalHours, totalHoursSpan.Minutes);



 Console.WriteLine(totalHrs);



}



输出:

 
04:20



 

string totalTime;


TimeSpan ts = new TimeSpan();


protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)


{


 if (e.Row.RowType == DataControlRowType.DataRow)


 {


 ts = ts.Add(TimeSpan.Parse((DataBinder.Eval(e.Row.DataItem, "Amount")));


 var hourPart = ((int)(Math.Truncate(ts.TotalMinutes/60))).ToString().PadLeft(2,'0');


 var minutePart = (ts.TotalMinutes%60).ToString().PadLeft(2,'0');


 totalTime = hourPart+":"+minutePart;


 }


}



...