c# - DateTimeFormatter.Format() 和字符串之间的区别

标签 c# .net uwp

DateTimeFormatter.Format的返回值应该是一个字符串。但是,当尝试解析 DateTimeFormatter 字符串的结果时(例如,新 DateTime 对象中的日期部分),它会抛出 "System.FormatException"

示例代码:

private void TestDateTimeFormatter()
{
    var forlatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("day");
    var casualDayFormat = forlatter.Format(new DateTime(2018, 1, 1));
    Console.WriteLine(casualDayFormat); // result is "1"
    var casualDateTime1 = DateTime.Parse("1" + ".1.2018"); //Works
    var casualDateTime = DateTime.Parse(casualDayFormat + ".1.2018"); //Throws wrong format exception
    Console.WriteLine(casualDateTime);
}

有些事情没有加起来。几乎可以肯定,casualDayFormat(它是一个字符串,值为“1”)和字符串 “1” 之间没有区别。但为什么会抛出异常?

编辑:异常详细信息

堆栈跟踪:

System.FormatException: String was not recognized as a valid DateTime.
       at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
//user-code 

异常_消息:

One of the identified items was in an invalid format.

其他方法:

事件 int.Parse(...) 不适用于字符串:

System.FormatException: Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

最佳答案

感谢 HansPassant,我找到了问题所在。当把字符串转为char数组时,我可以清楚地看到字符串中插入了隐藏的8206(从左到右)标记。

enter image description here

当使用以下命令从字符串中删除该字符时:

string output = new string(casualDayFormat.Where(c => c < 128).ToArray());

解析再次发挥作用。但是,作为 C# 开发人员,我不会排除 WinRT-API 的这种行为。

关于c# - DateTimeFormatter.Format() 和字符串之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51247757/

相关文章:

c# - 为 Windows 窗体应用程序启用快速启动的最佳实践 (.NET 4.0 C#)

c# - 为什么 Office Interop 引用在 VS 2010 中显示错误

c# - 单例模式 - 属性的不同值

c# - 为什么XML节点值不改变?

c# - 我如何获得一个月的最后一天?

.net - ASP.NET MVC : Best way to get form checkboxes into many-to-many DB assoc table with LINQ To SQL?

c# - DateTime.Parse 美国日期格式 C#

.net - 在 UWP 和 ASPNETCORE 应用程序上使用哪些类库作为引用

c# - UWP 应用未通过认证流程

c# - UWP App 返回上一页时随机崩溃