DateTime.ParseExact:"字符串未被识别为有效的DateTime" [英] DateTime.ParseExact: "String not recognised as a valid DateTime"
问题描述
我试图发送从JavaScript应用一个JSON请求,并在我的SQL数据库创建这个对象(HourRegistration),但由于某些原因,我不能解析来自JSON之日起,为有效日期时间。
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.
这是JS的 JSON日期
hourRegistration.Date = "12/08/2015";
所以 DD / MM / YYYY
我试图解析像这样:
Date = DateTime.ParseExact(hourRegistration.Date, "dd/MM/yyyy", CultureInfo.InvariantCulture)
整个方法
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();
}
ToCharArray()
我真的不知道为什么,这是行不通的。据我记得,这应该工作?
I don't really know why this doesn't work. As far as I recall, this should work?
推荐答案
在你的字符串值 hourRegistration.Date
不是你认为它是。
Your string value in hourRegistration.Date
is not what you think it is.
随着.NET串,还有一些要么不调试表示在所有出现许多Unicode字符或者事实上并非它们似乎是字符。在你的情况,由 ToCharArray
调试扩展显示,您的字符串实际上包含很多的 U + 200E
Unicode字符左至右符号'(U + 200E)字符。
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.
要解决您的眼前问题,解析您的日期之前,从你的字符串中删除所有非ASCII字符,沿着线:
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)
那么你应该能够解析 actualDateString
的要求。
Then you should be able to parse actualDateString
as required.
这篇关于DateTime.ParseExact:"字符串未被识别为有效的DateTime"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!