时间跨度转换失败
本文关键字:失败 转换 时间跨度 | 更新日期: 2023-09-27 18:36:19
在我的TimeIn.aspx文件中,我使用以下代码显示时钟:
<div>
<div>
<asp:ScriptManager runat="server" ID="ScriptManager1" />
<br />
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:Label runat="server" ID="Label4" Text="Current Time: "/>
<asp:Label runat="server" ID="Label2" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000" />
</div>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Check In" OnClick="CheckIn" />
</div>
时钟工作正常。然后在 TimeIn.aspx.cs 文件中,我编写了 CheckIn 方法:
protected void CheckIn(object sender, EventArgs e)
{
TimeSpan currtime = TimeSpan.Parse(Label2.Text);
int eid = Convert.ToInt32(Session["EID"]);
DBClient = new DBConnection();
DBClient.CheckIn(eid, currtime, DateTime.Now.Date.ToString());
Response.Redirect("ECheckin.aspx");
}
在"数据库"中,CheckinTime
列的数据类型为 Time(7)
。
当 CheckIn 事件触发时,它会在 TimeSpan.Parse 的第一行出现异常,因为 Label2.Text 添加了时间格式 (AM/PM) 的时间。
标签2.文本的示例值为:1:41:28 PM
处理这种情况的最佳解决方案是什么?我真的很想在 sql 服务器中使用Time
数据类型,因为稍后我将不得不对时间字段执行计算。
时间
跨度基本上是两个时间之间的差异。
或者我们可以说一个秒表,秒表中的值是自时钟开始和时钟停止以来经过的时间。
它与AM或PM无关。
Timespan = Date1 - Date2
我想你得到的错误将是格式异常
标签文本的格式DateTime
这就是 AM/PM 的原因。
尝试使用DateTime
实例,而不是时间跨度
喜欢
DateTime currtime = DateTime.Parse(Label2.Text);
您可以像下面这样将时间跨度添加到日期时间
TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt");
您可以直接传递时间跨度变量,而不是 03,00,00