开发者

how to concat date and time in c#?

Higuys,

I have a Textbox where user choose a date (MM/dd/yyyy) and another TextBox where choose inserts time (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="txtE开发者_Go百科ventDate"
                    PopupPosition="BottomLeft" Format="MM/dd/yyyy">
                </cc1:CalendarExtender>
            </td>
            <td>
                <asp:TextBox runat="server" ID="txtEventTime"></asp:TextBox>
            </td>
        </tr>

In the database I have a single column for DateTime so I have to "concatenate" the user input into a real datetime format...

I see a constructor for DateTime which takes as args: year, month, day, hour, minute, second, but this requires me to parse user input and split in these periods....

Do you know an easier solution?


You can use DateTime.ParseExact():

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


You should probably validate and/or trim the text from the textboxes before attempting any kind of concatenation.

    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)));

I would strongly suggest using JqueryUI to provide you with Date and Time pickers. Demos: http://jqueryui.com/demos/datepicker/

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


Use DateTime.ParseExact method.

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

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


You could do something like this:

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


You can use the DateTime.ParseExact method with an appropiate format string and your concattenated user input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜