2011-05-03 21 views
2

Higuys,如何在c#中连接日期和时间?

我有一个文本框,其中用户选择一个日期(MM/DD/YYYY)和另一种文本框,其中选择插入时间(HH:MM)。

<tr> 
      <td> 
       <asp:Label ID="Label1" runat="server" CssClass="cp_title">Event Date:</asp:Label> 
      </td> 
      <td> 
       <asp:Label ID="Label2" runat="server" CssClass="cp_title">Event Time(hh:mm):</asp:Label> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <asp:TextBox ID="txtEventDate" runat="server"> 
       </asp:TextBox> 
       <cc1:CalendarExtender ID="cldEventDate" runat="server" TargetControlID="txtEventDate" 
        PopupPosition="BottomLeft" Format="MM/dd/yyyy"> 
       </cc1:CalendarExtender> 
      </td> 
      <td> 
       <asp:TextBox runat="server" ID="txtEventTime"></asp:TextBox> 
      </td> 
     </tr> 

在数据库中,我有日期时间一个单列所以我要“串联”,用户输入一个真正的日期时间格式...

我看到的DateTime构造函数这需要作为参数:年,月,日,小时,分钟,秒,,但这需要我解析用户输入并在这些时间段内分割...

您知道更简单的解决方案吗?

+0

的[结合日期和时的日期是DateTime和时间是一个字符串时间]可能重复(http://stackoverflow.com/questions/3122015/combine-date- and-time-date-is-a-datetime-and-time-is-a-string) – Nix 2011-05-03 23:01:28

回答

6

您可以使用DateTime.ParseExact()

DateTime.ParseExact(txtEventDate.Text + " " + txtEventTime.Text, 
        "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture) 
+0

CultureInfo.InvariantCulture是什么意思? – jlg 2011-10-13 21:30:51

0

您可以将DateTime.ParseExact方法与适当的格式字符串和您的concattenated用户输入一起使用。

1

你可以做这样的事情:

string date = "1/2/2011"; 
string time = "12:15"; 
DateTime temp = Convert.ToDateTime(date + " " + time); 
2

使用DateTime.ParseExact方法。

string dateString = txtEventDate.Text + " " + txtEventTime.Text; 
string format = dateFormat + " " + timeFormat; 
DateTime result; 
CultureInfo provider = CultureInfo.InvariantCulture; 

result = DateTime.ParseExact(dateString, format, provider); 
6

在尝试任何类型的连接之前,您应该先验证和/或修剪文本框中的文本。

string _eventDate = "01/01/2011"; //in your case txtEventDate.Text 
    string _eventTime = "09:00 AM"; //in your case txtEventTime.Text 

    DateTime eventDate = Convert.ToDateTime(String.Format("{0} {1}",(_eventDate), _eventTime))); 

我强烈建议使用JqueryUI为您提供日期和时间选择器。 演示: http://jqueryui.com/demos/datepicker/

http://fgelinas.com/code/timepicker/

相关问题