如何将字符串转换为时间 [英] How to convert String to Time

查看:85
本文介绍了如何将字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



我有sqlDatareader从数据库和文本框中读取时间,从表单中抽出时间。我想比较两者。文本框时间转换为TimeSpan,如何将时间从阅读器转换为TimeSpan,以便我可以使用IF语句比较两者?

Hi all

I have sqlDatareader that reads time from database and textbox that takes time from a form. I want to compare the two. textbox time is converted into TimeSpan, How do I convert the time from the reader to TimeSpan so i can compare the two using IF statement?

TimeSpan starttime = TimeSpan.ParseExact(StartTime.Text, "HR:mm", CultureInfo.InvariantCulture);
TimeSpan endtime = TimeSpan.ParseExact(FinishTime.Text, "HR:mm", CultureInfo.InvariantCulture);


DateTime startTime = Convert.ToDateTime(reader["StartTime"]);
DateTime endTime = Convert.ToDateTime(reader["EndTime"]);



if     (startTime <= starttime && starttime <= endtime)
                {
                    
                    GridView1.Visible = false;


                }





我收到错误'starttime'和'endtime'不是以可识别的格式。并且if语句不起作用,因为'startTime'是datetime,'starttime'是TimeSpan。



有什么建议吗?

谢谢



I get error "The 'starttime' and 'endtime' is not in recognizable format." and also the if statement does not work as the 'startTime' is datetime and 'starttime' is TimeSpan.

Any suggestion please?
Thanks

推荐答案

我假设你在gridview中有标签和复选框控件,如下所示 -



I assume you have label and checkbox control in gridview something like below -

<asp:gridview runat="server" id="GridView1" autogeneratecolumns="false" onrowdatabound="GridView1_RowDataBound" xmlns:asp="#unknown">
   <columns>
      <asp:templatefield>
          <itemtemplate>
              <asp:label runat="server" id="label" text="labelControl"></asp:label>
              <asp:checkbox runat="server" id="checkbox" />
          </itemtemplate>
      </asp:templatefield>
   </columns>
 </asp:gridview>





然后您可以按如下方式访问它们 -





then you can access them as below -

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var label = e.Row.FindControl("labelControl") as Label;
        var checkBox = e.Row.FindControl("checkbox") as CheckBox;
    
        //Now set visibility on your condition here
        //label.Visible = true;
        //checkBox.Visible = true; 
    }
}





希望这会有所帮助。



hope this helps.


试试下面的代码



Try with below code

TimeSpan startTime = Convert.ToDateTime(reader["StartTime"]).TimeOfDay;
TimeSpan endTime = Convert.ToDateTime(reader["EndTime"]).TimeOfDay;


这篇关于如何将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆