I'm asking the same question as this: How can I parse relative dates with Perl? but in C#.
Sorry if this is a duplicate, ill delete if so.
Does such a library exist?
Thanks
I'm asking the same question as this: How can I parse relative dates with Perl? but in C#.
Sorry if this is a duplicate, ill delete if so.
Does such a library exist?
Thanks
using System;
using System.Text.RegularExpressions;
class RelativeDateParser
{
public static DateTime Parse(string input)
{
DateTime dt = DateTime.Now;
// parse "x days x hours x minutes x seconds" or "x days x hours x minutes x seconds ago"
Regex r = new Regex("(day)|(hour)|(minues)|(second)");
if (r.Match(input).Success == true)
{
dt = ParseDHMS(input, dt);
}
// parse "yesterday" or "today" or "tomorrow" or "eow" or "eod"
r = new Regex("(today)|(tomorrow)|(eow)|(eod)");
if (r.Match(input).Success == true)
{
dt = ParseGenericRelative(input);
}
Console.WriteLine("Now DateTime: " + DateTime.Now.ToString());
Console.WriteLine("New DateTime: " + dt.ToString());
return dt;
}
private static DateTime ParseGenericRelative(string input)
{
throw new NotImplementedException("Not implemented");
}
private static DateTime ParseDHMS(string input, DateTime seedDtm)
{
TimeSpan timeSpan = new TimeSpan(0);
// search for days
timeSpan += TimeSpan.FromDays(getMetricValue(input, "day"));
// search for hours
timeSpan += TimeSpan.FromHours(getMetricValue(input, "hour"));
// search for minutes
timeSpan += TimeSpan.FromMinutes(getMetricValue(input, "minutes"));
// search for seconds
timeSpan += TimeSpan.FromSeconds(getMetricValue(input, "second"));
return seedDtm.AddTicks(timeSpan.Ticks * (int)(input.EndsWith("ago") ? -1 : 1));
}
private static double getMetricValue(string input, string metric)
{
Regex r = new Regex(@"(\d+)\s*" + metric);
Match m = r.Match(input);
if (m.Success)
{
string match = m.Groups[1].Value;
return Double.Parse(match);
}
return 0;
}
}
Wayback Machine copy of original solution
Note: this implementation hasn't been tested