2016-09-01 3 views
1

dd/mm/yyyy hh:mm AM/PM 형식으로 날짜를 읽을 수있는 코드를 작성했지만 지금은 mm-dd-yyyy hh:mm Am/PM 인 경우 날짜 형식을 읽을 필요가 있습니다.잘못된 DateTime 형식

누군가 나를 올바른 방향으로 안내 할 수 있습니까?

내 코드 :이 코드는 01-02-2016 12:40 AM을 읽고 있지만, 내가 필요

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-15-2016 12:40 AM

답변

1

시도해보기 ike this

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); 
1

방법 : https://msdn.microsoft.com/fr-fr/library/8kb3ddd4(v=vs.110).aspx

: 손님의 날짜 구문 분석에 대한 참고로

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

+0

감사하지만 "{1/1/0001 12:00:00 AM}"이 모든 입력 값에 대해 반환됩니다. – vish1990