【问题标题】:TimeSpan Conversion FailsTimeSpan 转换失败
【发布时间】:2012-06-06 08:38:21
【问题描述】:

在我的 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)。
Label2.Text 的样本值为:1:41:28 PM
处理这种情况的最佳解决方案是什么?我真的很想在 sql server 中使用Time 数据类型,因为稍后我将不得不对时间字段执行计算。

【问题讨论】:

  • 将 label2.Text/Database 的值置于问题中。
  • In Database, the Datatype of CheckinTime column is Time(7).。是什么意思??
  • @Nikhil Agrawal 我使用 Sql Server 2008 作为后端数据库。在我的应用程序数据库表中,有一列 CheckinTime,其数据类型为 Time(7)。我想在该字段中存储签到时间。

标签: c# asp.net visual-studio-2010 sql-server-2008


【解决方案1】:

时间跨度基本上是两次之间的差异。

或者我们可以说秒表,其中秒表中的值是从时钟开始和时钟停止以来经过的时间。

与上午或下午无关。

Timespan = Date1 - Date2

我猜你得到的错误是FormatException

标签文本的格式是 DateTime,这就是 AM/PM 的原因。

尝试使用 DateTime 实例而不是时间跨度

喜欢

DateTime currtime = DateTime.Parse(Label2.Text);

【讨论】:

  • 我怀疑你的说法“时间跨度基本上是两次之间的差异”。 Timespan 是一个表示时间间隔的结构......就是这样。您的陈述导致人们认为时间跨度只能保持我认为错误的差异。
  • 你的评论支持我而不是反驳我。你说Timespan is a struct which represents a time interval。这就是我所说的。间隔只是差异。我选择了差异。您选择了间隔。一个和同一件事。名称是时间跨度,意思是两次之间的跨度。
  • @Nikhil Agrawal 您的代码也可以工作,但我通过在存储到数据库之前将时间转换为 24 小时格式来解决它:string d = DateTime.Now.ToString("HH:m:s"); TimeSpan currtime = TimeSpan.Parse(d); 谢谢
  • @NidaSulheri:看看你所做的就是我在回答中所说的。删除上午下午。您通过将其转换为 24 小时格式来做到这一点。正如你所说,它工作得很好。很高兴帮助你。超。
【解决方案2】:

您可以像下面那样将时间跨度添加到日期时间

  TimeSpan timespan = new TimeSpan(03,00,00);
    DateTime time = DateTime.Today.Add(timespan);
    string displayTime = time.ToString("hh:mm tt");

您可以直接传递时间跨度变量,而不是 03,00,00

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多