Reputation: 330
I am getting date and time from a combination of datepicker and timepicker add-on and want to store this date and time i.e. "26-11-2013 23:50" or "26-11-2013 11:50 PM" into SQL Server 2005 DateTime column. later on I want to use the dates to compare them like date1 > date2 etc.For this my .aspx is as follow:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<script>
$(document).ready(function () {
$("#MainContent_txtDate").datetimepicker({
dateFormat: "dd-mm-yy", changeYear: true, changeMonth: true, controlType: 'select',
timeFormat: 'hh:mm tt',
stepMinute: 15
});
});
</script>
<fieldset>
<legend>Add Journey</legend>
<h2>Add Journey</h2>
<ol>
<li>
<asp:Label AssociatedControlID="txtDate" runat="server">Date</asp:Label>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtDate" CssClass="field-validation-error" ErrorMessage="Required"></asp:RequiredFieldValidator>
</li>
</ol>
</fieldset>
</asp:Content>
in .aspx.cs I am doing
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(txtDate.Text, "d", provider);
Mytable.Column=date;
it gives FormatException. I tried DateTime date = DateTime.ParseExact(txtDate.Text, "dd-mm-yy hh:mm tt", provider);
but same result.
I do not want to use string for whole this purpose (but txtDate.Text gives string)
Upvotes: 1
Views: 822
Reputation: 499382
You have two different formats - one that is 24 hours and one that is with an AM/PM designator.
You need to try and parse with both - ParseExact
has an overload that takes an array of format strings, which is a suitable overload in this case:
var date = DateTime.ParseExact(txtDate.Text,
new string[] {"dd-MM-yyyy HH:mm", "dd-MM-yyyy hh:mm tt"},
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Now, the format string you have used - dd-mm-yy hh:mm tt
is using mm
incorrectly for months - it should be MM
for months, and mm
for minutes.
Upvotes: 0
Reputation: 6252
Try this for "26-11-2013 23:50":
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd-MM-yyyy HH:mm";
DateTime date = DateTime.ParseExact(txtDate.Text, format, provider);
Mytable.Column=date;
The hours should be HH
, this represent a 24-hourly clock. hh
is when you use AM/PM.
Upvotes: 1