|
using System;
using System.Text.RegularExpressions;
namespace TimeParserRegEx
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class FreeFormTimeParser
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
System.Console.WriteLine ("Enter time to be parsed: ");
string inputStr = System.Console.ReadLine ();
DateTime parsedTime = FreeFormTimeParser.ParseTime (inputStr);
System.Console.WriteLine ("The parsed time in long notation is: "
+ parsedTime.ToLongTimeString());
}
catch (FormatException e)
{
System.Console.WriteLine ("Invalid time format");
}
}
private const string TIME_STR =
@"^\s?(?<time>"
+ @"(?<hour>\d{1,2})"
+ @"(:(?<min>\d{1,2}))?"
+ @"\s?((?<am_pm>(am|pm)))?"
+ @")\s?$";
private static int ConvertAmPm (string amPm, int hour)
{
int retHour = hour;
amPm = amPm.ToLower();
if (amPm.Equals("am"))
{
// all hours remain the same except the 12:00 am (which is 0000 hours)
if (hour == 12)
retHour = 00;
}
else if (amPm.Equals("pm"))
{
// add 12 to hours except if 12:00 pm
if (hour != 12)
retHour = hour + 12;
}
else
throw new FormatException ("Invalid amPm flag format");
return retHour;
}
static DateTime ParseTime (string strTime)
{
DateTime currTime = DateTime.Now;
DateTime finalTime = DateTime.Today;
Match m;
int hour = 0,
min = 0;
Regex regExTime = new Regex (TIME_STR,
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
m = regExTime.Match (strTime);
if (m.Success)
{
if (m.Groups["hour"].Success)
hour = Int32.Parse (m.Groups["hour"].Value);
if (m.Groups["min"].Success)
min = Int32.Parse (m.Groups["min"].Value);
if (m.Groups["am_pm"].Success)
{
hour = ConvertAmPm (m.Groups["am_pm"].Value, hour);
}
}
else
throw new FormatException ("Invalid time format");
if (hour > 23 || min > 59)
throw new FormatException ("Invalid time format");
finalTime = new DateTime (currTime.Year, currTime.Month, currTime.Day,
hour, min, 0);
return finalTime;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.