如何将char数组转换为DateTime.Parse的字符串? [英] How to convert char array into string for DateTime.Parse?

查看:52
本文介绍了如何将char数组转换为DateTime.Parse的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的控制器中使用它:

I am using this in my controller:

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:无法将字符串识别为有效的DateTime.

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" 字符串 + char = 字符串
  • '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

这篇关于如何将char数组转换为DateTime.Parse的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆