【问题标题】:Display Time in input control type of time在时间输入控制类型中显示时间
【发布时间】:2019-03-03 19:52:45
【问题描述】:

在 C# 中,我有一个 DateTime 字段,我只想在“时间”类型的输入控件中显示时间。

现场示例:

<asp:TextBox ID="txtStartTime" runat="server" MaxLength="10" CssClass="form-control" type="time"></asp:TextBox>

这些都不行:

txtStartTime.Text = ((System.DateTime)pDS.Tables[0].Rows[0]["StartTime"]).ToShortTimeString(); 

System.String strResult = System.String.Format("{0:hh:mm tt}", pDS.Tables[0].Rows[0]["StartTime"].ToString());
txtStartTime.Text = strResult;

【问题讨论】:

  • 去掉 string.Format 行中的 ToString 就可以了

标签: c# html


【解决方案1】:

使用DateTime类本身的ToString(format)方法:

DateTime dt = ((System.DateTime)pDS.Tables[0].Rows[0]["StartTime"]);
txtStartTime.Text = dt.ToString("hh:mm:ss");

【讨论】:

    【解决方案2】:

    String.Format 需要一个对象来应用该格式。文档告诉我们方法:

    用指定对象的字符串表示形式替换字符串中的一个或多个格式项。

    string 的字符串表示是string 本身。所以你的格式字符串对你传递给它的字符串没有影响。 但它可以格式化 Datetime 对象,因为您使用的格式具有有效的字符串表示匹配。

    因此,只需删除 ToString 调用,您的方法就会奏效。

    System.String strResult = System.String.Format("{0:hh:mm tt}", pDS.Tables[0].Rows[0]["StartTime"]);
    txtStartTime.Text = strResult;
    

    【讨论】:

      【解决方案3】:

      使用Datetime.ToString(String)
      要获取小时格式,只需使用 ToString("hh:mm:ss")

      例子:

       <%
      
              var dt = DateTime.Now;//((System.DateTime)pDS.Tables[0].Rows[0]["StartTime"]);
              txtStartTime.Text = dt.ToString("hh:mm:ss");
      
          %>
      
          <!DOCTYPE html>
      
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head runat="server">
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
              <title></title>
          </head>
          <body>
              <form id="form1" runat="server">
                  <asp:TextBox ID="txtStartTime" runat="server" MaxLength="10" CssClass="form-control" type="time"></asp:TextBox>
              </form>
          </body>
          </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 2021-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多