如何将 DateTime.Parse 的字符数组转换为字符串?
How to convert char array into string for DateTime.Parse?
我在我的控制器中使用这个:
char[] arrDate = date.ToArray();
DateTime dt = DateTime.Parse(arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]);
错误:
System.FormatException: String was not recognized as a valid DateTime.
考虑一下:
var date = "11252017";
var arrDate = date.ToArray();
var strDate = arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]; // 98/25/2017
注意:
'1' + '1' = 98
* ⇒ char
+ char
= int
98 + "/" = "98/"
⇒ int
+ string
= string
"98/" + '2' = "98/2"
⇒ string
+ char
= string
修复:
var dt = DateTime.Parse("" +
arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]);
*ASCII表示:
'1'
的十进制是 49
我假设 date
是 string
类型。对于解析字符串,DateTime
class 有几种方法,ParseExact
是其中一种。此方法可以在给定格式说明符和区域性的情况下解析字符串。在您的情况下,日期可以这样解析:
var date = "11252017";
var dt = DateTime.ParseExact(date, "MMddyyyy", CultureInfo.InvariantCulture);
顺便说一下,string
是 char
的数组,因此在您的代码中 arrDate[0]
与 date[0]
完全相同。只是为了将来记住一些事情。
我在我的控制器中使用这个:
char[] arrDate = date.ToArray();
DateTime dt = DateTime.Parse(arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]);
错误:
System.FormatException: String was not recognized as a valid DateTime.
考虑一下:
var date = "11252017";
var arrDate = date.ToArray();
var strDate = arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]; // 98/25/2017
注意:
'1' + '1' = 98
* ⇒char
+char
=int
98 + "/" = "98/"
⇒int
+string
=string
"98/" + '2' = "98/2"
⇒string
+char
=string
修复:
var dt = DateTime.Parse("" +
arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]);
*ASCII表示:
'1'
的十进制是49
我假设 date
是 string
类型。对于解析字符串,DateTime
class 有几种方法,ParseExact
是其中一种。此方法可以在给定格式说明符和区域性的情况下解析字符串。在您的情况下,日期可以这样解析:
var date = "11252017";
var dt = DateTime.ParseExact(date, "MMddyyyy", CultureInfo.InvariantCulture);
顺便说一下,string
是 char
的数组,因此在您的代码中 arrDate[0]
与 date[0]
完全相同。只是为了将来记住一些事情。