我在TextBox
表单上有一个asp.net
控件,用于输入Date
来自用户。和另一个TextBox
控件进入Time
。
现在,我想要将这两个字段合并并保存到DataBase。
示例:05/25 / 1987 + 10.30PM
结果于05/25/1987 10:30 PM
现有代码:
public DateTime? DueDate { get; set; }
DateTime? dd = new DateTime();
if (!string.IsNullOrEmpty(txtDueDate.Text))
{
dd = Convert.ToDateTime(txtDueDate.Text.ToString().Trim());
}
else
{
dd =null ;
}
objBB.DueDate = dd;
HTML标记:
<strong> Due Date:</strong> <asp:TextBox ID="txtDueDate" runat="server" CssClass="txtadmincms" Width="110px"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDueDate">
</cc1:CalendarExtender>
<strong> Time:</strong> <asp:TextBox ID="txtTime" runat="server" CssClass="txtadmincms" Width="110px"></asp:TextBox>
<cc1:MaskedEditExtender ID="meeStartTimePunchIn" runat="server" AcceptAMPM="true"
MaskType="Time" Mask="99:99" MessageValidatorTip="true" OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError" ErrorTooltipEnabled="true" UserTimeFormat="None"
TargetControlID="txtTime" InputDirection="LeftToRight" AcceptNegative="Left">
</cc1:MaskedEditExtender>
更新:
如果TIME
字段TextBox
为空,则会在其他部分
if (!string.IsNullOrEmpty(txtDueDate.Text))
{
dd = Convert.ToDateTime(txtDueDate.Text.ToString().Trim());
if (!string.IsNullOrEmpty(txtTime.Text))
{
ddateTime = DateTime.ParseExact(txtDueDate.Text.ToString() + txtTime.Text.ToString(), "MM-dd-yyyy HH:mm", CultureInfo.InvariantCulture);
}
else
{
ddateTime = DateTime.ParseExact(txtDueDate.Text.ToString(), "MM-dd-yyyy HH:mm", CultureInfo.InvariantCulture);
}
dd = ddateTime;
//Combine here date & time
}
else
{
dd =null ;
}
objBB.DueDate = dd;
帮助感谢!
答案 0 :(得分:3)
您可以使用DateTime.Parse
或DateTime.ParseExact
:
string dateAndTime = txtDueDate.Text.Trim() + ' ' + txtTime.Text.Trim(); // 05/25/1987 10:30PM
DateTime dt = DateTime.ParseExact(dateAndTime, "MM/dd/yyyy hh:mmtt", CultureInfo.InvariantCulture, DateTimeStyles.None);
dt = DateTime.Parse(dateAndTime, CultureInfo.InvariantCulture, DateTimeStyles.None);
答案 1 :(得分:2)
您可以尝试将两个字符串合并为一个然后解析它:
string datePart = txtDueDate.Text.ToString().Trim();
string timePart = txtTime.Text.ToString().Trim();
string dateTime = string.Format("{0} {1}", datePart, timePart);
dd = DateTime.Parse(dateTime);
要考虑的事情:
TryParse
代替Parse
进行输入验证答案 2 :(得分:0)
试试这个
DateTime dt =
DateTime.ParseExact(txtDueDate.Text.ToString()+txtTime.Text.ToString(),
"MM-dd-yyyy HH:mm", CultureInfo.InvariantCulture);