2015-09-28 35 views
2

在VS2015中转换字符串时出现奇怪的错误。当我使用x变量时,我没有错误。只有当我使用日期变量时引发异常。任何想法为什么?当在C中将简单的数字字符串转换为Int时,引发格式异常#

感谢

代码:

using System; 
using System.Globalization; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string x = "9-1-2015"; 
      string date = "‎9‎-‎1-‎2015"; 
      List<string> dt = date.Split('-').ToList(); 
      List<int> lis = new List<int>(); 
      foreach (var item in dt) 
      { 
       lis.Add(int.Parse(item)); 
      } 
     } 
    } 
} 
+9

您的'日期'变量值包含不可打印的字符 - U + 200E在这种情况下。 (将你的字符串复制并粘贴到http://csharpindepth.com/Articles/General/Unicode.aspx#explorer中查看我的意思。)不知道它们来自哪里,很难知道要建议什么,但它不是转换“简单数字字符串”的问题。 –

+0

您是否特意插入该符号以提高评分? – 2015-09-28 12:05:00

+0

我从MVC中的kendoDatePicker Jquery Ajax POST值中粘贴它。任何想法如何将这些字符串转换为可转换格式。谢谢。 –

回答

0

感谢蒂姆Schmelter。

是的确的,我需要清理我的字符串变种。你的代码非常有用,但它不适用于我的代码。所以我将代码修改为下面的代码。然后我可以将cleanDate var解析为DateTime对象。

string date = "9/28/2015 12:00:00 AM"; // In My Code, This Var Contain Unseen Unicode Char. 
    var cleanDate = new string(date.Where(c => char.IsNumber(c) || char.IsPunctuation(c) || char.IsWhiteSpace(c) || char.IsLetter(c)).ToArray()); 
    DateTime date = DateTime.ParseExact(cleanDate, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture); 
0

在代码中,线下有一些隐藏的空间:

string date = "‎9‎-‎1-‎2015"; 

尝试在这条线移动与键盘箭头光标,你会得到我的观点。

尝试删除这条线和手动改写此行的代码(没有复制粘贴),也将努力

1

由于乔恩斯基特has pointed out

您的日期变量值中包含非打印字符,副本和你的字符串粘贴到http://csharpindepth.com/Articles/General/Unicode.aspx#explorer

所以,你必须改变它的产生或方式,如果那是不可能的/期望的,你把它解析到之前将其删除(这是你真正想要的)。

您可以使用此方法:

var unicodeCategories = new[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DashPunctuation }; 
string cleanDate = string.Concat(date.Where(c => unicodeCategories.Contains(char.GetUnicodeCategory(c)))); 

现在你可以使用DateTime.TryParseExact

DateTime dt; 
if (DateTime.TryParseExact(cleanDate, "d-M-yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt)) 
    Console.WriteLine("Year:{0} Month:{1} Day:{2}", dt.Year, dt.Month, dt.Day); 
else 
    Console.WriteLine("Could not be parsed to DateTime"); 

输出与dateYear:2015 Month:1 Day:9

+0

我认为应该首先确定这些角色来自哪里。在其中一条评论中,OP表示他使用了剑道日期选择器;这些字符已经存在于请求体中(所以解决方法应该在客户端找到)?还是在请求处理管道期间它们添加到服务器端的某个地方? – jeroenh

相关问题