d_li1121 d_li1121 - 1 year ago 68
C# Question

Updating DateTime value into database with strange format shows incorrect Date

I'm using a a jQuery datepicker to have users enter a date in a text box. The date is then displayed on the webpage in the 2 digit month, day, and 2 digit year format with out slashes mmddy

$(function() {
$("#datepicker").datepicker({ dateFormat: 'mmddy' });

When this date is entered it is displayed on the page correctly, but the date in the database does not reflect the date entered in the textbox. Instead I'll have a date entered with the correct, day, and year, but not month.

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt new DateTime();
dt = DateTime.ParseExact(datepicker.Text, "mmddy", provider);

cmd.Parameters.AddWithValue("@date", dt);

//result example 2016-01-09 hh:mm:ss the should be 2016-09-09

I've tried converting to string. I've tried the different Parsing methods (
, etc.) It will either return the same results in the database, or I'll get errors such as an invalid date format or where the date is less than the the minimum date that can be entered in the database. I don't want to use
because while it works, I'm using a checker where if the user enters a future date it will update to the future date and using DateTime.Now will always enter the current date. The datetype in my table is datetime, using an old version of sql, and
is allowed.

Answer Source

Your format string mmddy is incorrect.

You need to use capital Ms for month as lowercase ms signify minutes:


"M" The month, from 1 through 12.

"MM" The month, from 01 through 12.

"MMM" The abbreviated name of the month.

"MMMM" The full name of the month.

Reference Custom Date Time Formats

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download