While working with dates sometimes we need to join Date and Time values into single DateTime value.We can implement this using the methods of the DateTime class.
To convert a string representation of a date time value to datetime datatype ParseExact method of DateTime type is used.
It returns a DateTime value for the passed string value which represents a DateTime.
To create a datetime value from the date and time values in different TextBoxes we follow the below steps
1.Read the string value in the first TextBox. This is the string value representing a date.
In .aspx page <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> In code behind DateTime dateValue = txtDate.Text;
2.Convert the above string value to a DateTime value using the ParseExact() method.
DateTime dtDate = DateTime.ParseExact(dateValue.Text, "yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture);
3.Read the string value in the second TextBox. This is the string value representing time.
In aspx page <asp:TextBox ID="txtTime" runat="server"></asp:TextBox> In codebehind var timeValue = txtTime.Text;
4.Convert the above time value string to a DateTime value using the ParseExact() method.
var dtTime = DateTime.ParseExact(timeValue, "HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
5.Finally combine the date and time components using a DateTime constructor.We pass the different date and time components
to this constructor.This logic we can include in the button click event.
protected void Button1_Click(object sender, EventArgs e) { DateTime dtComplete= new DateTime(dtDate.Year, dtDate.Month, dtDate.Day,dtTime.Hour,dtTime.Minute,dtTime.Second); }
Leave a Reply