bonCodigo
bonCodigo

Reputation: 14361

Issue when converting or casting Date String to DateTime

I am using jQuery DatePicker to retrieve date for a textbox in Gridview for inserting/updating records. The datepicker's date is received as a String. e.g. value "07/31/2014".

Using following code I am converting string date into a C# DateTime.

    var sDate = ((TextBox)row.FindControlRecursive("iStartDateTBox")).Text;
    payment.StartDate = DateTime.ParseExact(sDate, "mm/dd/yyyy", null);

However once converted, the value set to payment's Start Date property becomes "31/01/2014 12:07:00" I am just perplexed about what's really happening. And would like few tips to solve this.

Upvotes: 0

Views: 227

Answers (2)

Pavel Pája Halbich
Pavel Pája Halbich

Reputation: 1583

You can use DateTime.ParseExact with IFormatProvider. ( MSDN )

So try something like this:

var result = DateTime.TryParse(
      "10. 10. 2014", 
      CultureInfo.CreateSpecificCulture("en-US"), 
      DateTimeStyles.None,
      out date);

Upvotes: 1

bonCodigo
bonCodigo

Reputation: 14361

It was just a matter of the date time formatting. When using DateTime, the code MM refers to month, where as mm refers to minutes...

THIS

payment.StartDate = DateTime.ParseExact(sDate, "mm/dd/yyyy", null);

SHOULD BE

payment.StartDate = DateTime.ParseExact(sDate, "MM/dd/yyyy", null);

Upvotes: 1

Related Questions