我使用了三个文本框控件,在第一个文本框中我指定了开始时间,在第二个文本框中我指定了结束时间,当控件移动到下一个文本框时,应该自动计算持续时间。我已经看到了一些使用时间跨度的建议,但它不能100%完美地工作。例如,
如果开始时间=上午10.00,结束时间= 03:00 PM,则持续时间计算为5小时,但如果开始时间= 03:00 PM,结束时间= 01:00 AM,则持续时间= -14:00以错误的方式。我期望的输出在顺时针方向上是= 10小时,而是以逆时针方向计算时间,并且输出错误为-14:00。如何克服这种情况。我发布了我在下面使用的代码。
<div>
<asp:Label ID="lblStartTime" runat="server" Text="StartTime"></asp:Label>
<asp:TextBox ID="txtstrtime" runat="server" Width="88px" AutoPostBack="True"
Height="25px" ontextchanged="txtstrtime_TextChanged"></asp:TextBox>
<asp:MaskedEditExtender ID="txtstrtime_MaskedEditExtender" runat="server"
TargetControlID="txtstrtime" Mask="99:99" MessageValidatorTip="true"
MaskType="Time" InputDirection="RightToLeft" Enabled="true" AcceptAMPM="true">
</asp:MaskedEditExtender>
<asp:Label ID="lblEndTime" runat="server" Text="EndTime"></asp:Label>
<asp:TextBox ID="txtendtime" runat="server" Width="97px" Height="25px"
AutoPostBack="True" ontextchanged="txtendtime_TextChanged">
</asp:TextBox>
<asp:MaskedEditExtender ID="txtendtime_MaskedEditExtender" runat="server"
Mask="99:99" MessageValidatorTip="true" MaskType="Time"
InputDirection="RightToLeft" Enabled="true" TargetControlID="txtendtime"
AcceptAMPM="true">
</asp:MaskedEditExtender>
<asp:Label ID="lblduration" runat="server" Text="Duration"></asp:Label>
<asp:TextBox ID="txtduration" runat="server" Width="112px" Height="27px"
ontextchanged="txtduration_TextChanged" AutoPostBack="True"></asp:TextBox>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
</div>
,背后的代码是
protected void txtendtime_TextChanged(object sender, EventArgs e)
{
try
{
DateTime startTime, endTime;
startTime = Convert.ToDateTime(txtstrtime.Text);
endTime = Convert.ToDateTime(txtendtime.Text);
var timeDiff = new TimeSpan(endTime.Ticks - startTime.Ticks);
txtduration.Text = Convert.ToString(timeDiff);
txtduration.Focus();
}
catch
{
}
}
答案 0 :(得分:2)
将以上内容添加到txtDuration.Text:
if (timeDiff.TotalSeconds < 0) {
timeDiff.Add(TimeSpan.FromDays(1));
}
答案 1 :(得分:1)
试试这个。
protected void txtendtime_TextChanged(object sender, EventArgs e)
{
try
{
DateTime startTime, endTime;
startTime = Convert.ToDateTime(txtstrtime.Text);
endTime = Convert.ToDateTime(txtendtime.Text);
if (startTime > endTime)
endTime = endTime.AddDays(1);
TimeSpan span = (toDate - fromDate);
double actualHours = Math.Round(span.TotalHours, 2);
txtduration.Text = Convert.ToString(actualHours);
txtduration.Focus();
}
catch
{
}
}
答案 2 :(得分:1)
试试这个:
DateTime startTime, endTime;
TimeSpan timeDiff;
startTime = Convert.ToDateTime(txtstrtime.Text);;
endTime = Convert.ToDateTime(txtendtime.Text);
if (startTime > endTime)
{
timeDiff = new TimeSpan(startTime.Ticks - endTime.Ticks);
}
else
{
timeDiff = new TimeSpan(endTime.Ticks - startTime.Ticks);
}
txtduration.Text = Convert.ToString(timeDiff );