DateMath parses and applies Elasticsearch-style date math expressions in .NET. It supports expressions anchored to the current UTC time or a specific date, arithmetic with common date units, and rounding.
The package targets .NET Standard 2.0, making it compatible with modern .NET and .NET Framework 4.6.1 or later. Microsoft recommends .NET Framework 4.7.2 or later when consuming .NET Standard 2.0 libraries.
Install the package with the .NET CLI:
dotnet add package DateMathOr with the NuGet Package Manager Console:
Install-Package DateMathExpressions can use now as their anchor:
using DaleNewman;
DateMath.Parse("now", "yyyy-MM-dd h tt");
DateMath.Parse("now+11h", "yyyy-MM-dd h tt");
DateMath.Parse("now-13h+1y+1d-1s", "yyyy-MM-dd HH:mm:ss");
DateMath.Parse("now/d", "yyyy-MM-dd HH:mm:ss.fff");A fixed anchor date is separated from its math expression by ||:
var result = DateMath.Parse("2016-12-31 1 PM||+11h", "yyyy-MM-dd h tt");
// 2017-01-01 12 AMUse TryParse when you need to check whether parsing succeeded:
if (DateMath.TryParse("now+11h", out DateTime date))
{
// Use date.
}Use Apply when you already have a date:
var date = new DateTime(2016, 12, 31, 9, 30, 2);
var newYears = DateMath.Apply(date, "+1d/y");
// 2017-01-01 00:00:00| Unit | Meaning |
|---|---|
y |
Year |
M |
Month |
w |
Week |
d |
Day |
h |
Hour |
m |
Minute |
s |
Second |
Prefix a unit with + or - to add or subtract it, such as now-10d. Prefix it with / to round down, such as now/M for the start of the current month.
Common reporting ranges include:
| Range | Start | End |
|---|---|---|
| Last 10 days | now-10d |
now |
| Month to date | now/M |
now |
| Year to date | now/y |
now |
| Sliding 60-day window | now-30d |
now+30d |
See the tests for more examples, the changelog for release history, and the NuGet packaging guide for local release instructions.
Issues and pull requests are welcome in the GitHub repository. Build and test locally with:
dotnet test --configuration ReleaseDateMath is licensed under the Apache License 2.0.