David Smith

David Smith

  • NA
  • 2k
  • 0

Array Sequence TimeStamp Validation

Aug 21 2013 1:17 PM
I am getting an error below that the string is not a valid datetime format. Can someone help below.

using System;
using System.Linq;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
       string[] ArrayElement = new string[6];
       ArrayElement[0]= "1:05:00 PM 06/25/2013 On True";
       ArrayElement[1]= "1:10:00 PM 06/25/2013 Off True";
       ArrayElement[2]= "1:15:00 PM 06/25/2013 On True";
       ArrayElement[3]= "1:20:00 PM 06/25/2013 Off True";
       ArrayElement[4]= "1:25:00 PM 06/25/2013 On True";
       ArrayElement[5]= "1:30:00 PM 06/25/2013 Off True";
 
       Console.WriteLine(Validate(ArrayElement)); // True  

       ArrayElement[2]= "1:15:00 PM 05/25/2013 On True";
       Console.WriteLine(Validate(ArrayElement)); // False  
       Console.ReadKey();  
    }

    static bool Validate(string[] state)
    {
       string f = "h:mm:ss tt MM/dd/yyyy";
 
       // extract time stamps and make sure they're in sequence
       DateTime[] stamps = state
       .Select(s => DateTime.ParseExact(s.Substring(0, s.LastIndexOf(" ")), f, null)).ToArray();
       for(int i = 1; i < stamps.Length; i++)
       {
           if(stamps[i] < stamps[i-1]) return false;
       }

       // extract On/Off's and validate them
       state = state.Select(s => s.Substring(s.IndexOf("O"))).ToArray();
       string text = String.Join("", state);
       string regExp = "^(OnOff)+$";
       return Regex.IsMatch(text, regExp);
    }
}

Answers (23)