DateTime格式不正确

时间:2016-09-01 09:43:47

标签: c# date datetime

我编写的代码可以用<Identity Name="COM.CordovaApp" Publisher="CN=11111111-2222-3333-444444444444" Version="2.2.11.0" /> 格式读取日期,但现在我需要它以dd/mm/yyyy hh:mm AM/PM格式读取日期。

有人可以指导我正确的方向吗?

我的代码:

mm-dd-yyyy hh:mm Am/PM

此代码正在阅读IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true); foreach (FileInfo fi in fiArray) { try { StreamReader reader = fi.OpenText(); string date; string logContent = reader.ReadLine(); string patternDate = "(?<logDate>(\\d){2}-(\\d{2})-(\\d{4})\\s(\\d{2}):(\\d{2})\\s?(?i)(am|pm))"; Regex reg = new Regex(patternDate); date = reg.Match(logContent).Value.ToString(); // for dt2, the error happens here DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal); // DateTime dt2 = DateTime.ParseExact(date, format, provider); while ((line = reader.ReadLine()) != null) { Regex reg1 = new Regex("^(ARCH(?!9{2}))"); bool flag = reg1.IsMatch(line); if (flag == true) { string dt = DateTime.Now.ToString("yyyymmddHHMMss"); string[] values = line.Split(',').Select(sValue => sValue.Trim()).ToArray(); // string uniqueGuid = SequentialGuidGenerator.NewGuid().ToString(); string uniqueGuid = Utility.generateID(); uniqueGuid = uniqueGuid.Replace("-", "").Substring(0,18); string RPT_ID = values[0].ToString(); RPT_ID = RPT_ID.Remove(0, 4); table.Rows.Add(uniqueGuid, RPT_ID, values[1].ToString(), dt2); } else { } } reader.Close(); } catch (MyException e) { throw e.MyExceptiona(e, fi); } } Utility.InsertData(table); 但我需要阅读01-02-2016 12:40 AM

2 个答案:

答案 0 :(得分:1)

怎么样:

DateTime mydt;
DateTime.TryParseExact("01-16-2016 12:40 AM", "MM-dd-yyyy hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out mydt)

有关自定义日期时间解析的参考:https://msdn.microsoft.com/fr-fr/library/8kb3ddd4(v=vs.110).aspx

答案 1 :(得分:1)

试试这个

DateTime parsedDate ;
string YourDate = "01-15-2016 12:40 AM";
string pattern = "MM-dd-yyyy hh:mm tt";
DateTime.TryParseExact(YourDate, pattern, null,
                               DateTimeStyles.None, out parsedDate);