我以前使用以下代码对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
答案 0 :(得分:1)
您可以使用TimeSpan.FromMinutes(minutesInDouble),以双精度格式传递上述值。
答案 1 :(得分:1)
您可以尝试以下操作:
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
答案 2 :(得分:0)
您可以使用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;
}
答案 3 :(得分:0)
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;
}
}