Created
June 16, 2021 20:54
-
-
Save cgillis-aras/ab67e39d7a271a88566eafa54aadea5c to your computer and use it in GitHub Desktop.
Sample code of using a Regular Expression to turn a string representation of an excel-like date formula into an actual date value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public string EvaluateDateCalculation(string dateValue) | |
{ | |
string dateFormula = @"(?:([0-9]+)[\s]*([+-])[\s]*)?(TODAY\(\))(?:[\s]*([+-])[\s]*([0-9]+))?"; | |
System.Text.RegularExpressions.Regex dateRegex = new System.Text.RegularExpressions.Regex(dateFormula); | |
System.Text.RegularExpressions.Match dateMatch = dateRegex.Match(dateValue); | |
if (dateMatch.Success) | |
{ | |
System.Text.RegularExpressions.GroupCollection calcGroups = dateMatch.Groups; | |
// Find the base date (Right now, only TODAY() is supported, but something like DATE(1, 1, 2021) might be supported later) | |
var baseDateGroup = calcGroups[3]; | |
DateTime dateToReturn = new DateTime(); | |
if (baseDateGroup.Value == "TODAY()") | |
{ | |
dateToReturn = DateTime.Now; | |
} | |
dateToReturn = HandleDateChange(dateToReturn, calcGroups[1], calcGroups[2]); | |
dateToReturn = HandleDateChange(dateToReturn, calcGroups[5], calcGroups[4]); | |
// In order to have this actually be useful as a query, we need to set up a condition to get all dates that lie between | |
// Midnight and 11:59 PM (or 23:59) of the selected date | |
string midnightDateFormat = "yyyy-MM-ddT00:00:00"; | |
string lastMinuteFormat = "yyyy-MM-ddT23:59:59"; | |
return $"{dateToReturn.ToString(midnightDateFormat)} and {dateToReturn.ToString(lastMinuteFormat)}"; | |
} | |
// If our regular expression did not match anything, then that means | |
// this is just a normal date that we can pass along without modification | |
return dateValue; | |
} | |
public DateTime HandleDateChange(DateTime date, System.Text.RegularExpressions.Group numDaysGroup, System.Text.RegularExpressions.Group modifierGroup) | |
{ | |
if (numDaysGroup.Success && modifierGroup.Success) | |
{ | |
int numDays = Int32.Parse(numDaysGroup.Value); | |
string modifier = modifierGroup.Value; | |
return date.AddDays((modifier == "+") ? numDays : (numDays * -1)); | |
} | |
// Just return the base date if the groups were not found | |
return date; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment