I'm trying to send a JSON request from a javascript application, and create this object (HourRegistration) in my SQL DB, but for some reason, I can't parse the date from json, to a valid DateTime.
JSON date from JS
hourRegistration.Date = "12/08/2015";
So dd/MM/yyyy
I'm trying to parse like so:
Date = DateTime.ParseExact(hourRegistration.Date, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Entire method
public void CreateHours(HourRegistrationDTO hourRegistration)
{
DAO.Instance.HourRegistration.Add(new HourRegistration()
{
Date = DateTime.ParseExact(hourRegistration.Date, "dd/MM/yyyy", CultureInfo.InvariantCulture),
Cust_ID = hourRegistration.Cust_id,
Login_ID = hourRegistration.Login_id,
Hours = hourRegistration.Hours,
Comment = hourRegistration.Comment
});
DAO.Instance.SaveChanges();
}
Screenshot
ToCharArray()
I don't really know why this doesn't work. As far as I recall, this should work?
Your string value in hourRegistration.Date
is not what you think it is.
With strings in .NET, there are many Unicode characters which either do not appear at all in the debug representation, or are not in fact the characters they appear to be. In your case, as shown by the ToCharArray
debug expansion, your string actually contains a number of U+200E
Unicode Character 'LEFT-TO-RIGHT MARK' (U+200E) characters.
These are invisible in the debug representation, but ARE relevant when trying to parse the date. I don't know how they got there or why they are there - that's something you'd need to research further.
To solve your immediate issue, before parsing your date, remove all non-ASCII characters from your string, along the lines of:
var actualDateString = new String(hourRegistration.Date
.ToCharArray()
.Where(c => c <= 255)
.ToArray()
);
(I've just banged this out so it's not very pretty)
Then you should be able to parse actualDateString
as required.
This gives no error:
DateTime date = DateTime.ParseExact("12/08/2015", "dd/MM/yyyy", CultureInfo.InvariantCulture);
, so the problem has to be somewhere else.
I have to assume that your hourRegistration.Date
variable is empty string. In that case you get the exception "String was not recognized as a valid DateTime."
Debug the value before parsing.
EDIT
Based on your comment it shoud be no problem to give us a screen capture like this:
Just to make sure and clarify the problem scope... Thanks!
EDIT 2
This could sound weird:
Try renaming your string
property and see if it's fixing the issue.
See the following behavior on a string
object called Date
Can someone tell me why is handled as DateTime
object in debugger? it's clearly a string
variable.
Update: This issue has been detailed here: String variable name Date acts weird in debugger
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With