I have strings in format of "yyyyMMdd". I would like to convert them into DateTime with the format but I get an error that says the string is not valid as a DateTime string. How can I do this?
问问题
13597 次
5 回答
6
用于DateTime.ParseExact
指定格式和不变的文化:
var date = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
于 2013-07-01T13:03:19.390 回答
4
DateTime dt;
DateTime.TryParseExact(textBox.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
于 2013-07-01T13:03:25.580 回答
4
使用DateTime.ParseExact
:
string dateString = "20130701";
DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", null, DateTimeStyles.None);
于 2013-07-01T13:03:37.893 回答
0
这个问题以前被问过并回答过。但这里是一个工作代码的例子:
string DateString = "20130701";
DateTime DT = DateTime.ParseExact(DateString, "yyyyMMdd", CultureInfo.InvariantCulture);
哪里CultureInfo.InvariantCulture
是 System.Globalization 命名空间的一部分。
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.71).aspx
于 2013-07-01T13:09:10.747 回答
-2
将它们分解为 DateTime.Parse 将接受为有效的格式。您甚至可以使用正则表达式来解析信息
Regex format = new Regex("(?<year>^[0-9]{4})(?<month>[0-9]{2})(?<day>[0-9]{2})");
Match m = format.Match(inputString);
int year = int.Parse(m.Groups["year"].Value;
int month = int.Parse(m.Groups["month"].Value;
int day = int.Parse(m.Groups["day"].Value;
DateTime date = new DateTime(year, month, day);
于 2013-07-01T13:07:26.747 回答