我可以使用什么库来根据日期表达式计算日期?
日期表达式类似于:
- “+3D”(加三天)
- “-1W”(减去一周)
- “-2Y+2D+1M”(减2年,加1天,加1个月)
例子:
DateTime EstimatedArrivalDate = CalcDate("+3D", DateTime.Now);
预计到达日期等于当前日期加上 3 天。
我听说过 JodaTime 和 NodaTime,但我还没有在它们中看到任何这样做的东西。我应该使用什么来在 C# 中获得此功能?
没有库(我知道,包括 JodaTime 到 .NET 的端口)可以与这样的表达式一起使用。只要表达式被简单地链接起来(就像在您的示例中那样),编写一个正则表达式来解析该表达式并自己进行处理应该很容易:
public static DateTime CalcDate(string expression, DateTime epoch)
{
var match = System.Text.RegularExpressions.Regex.Match(expression,
@"(([+-])(\d+)([YDM]))+");
if (match.Success && match.Groups.Count >= 5)
{
var signs = match.Groups[2];
var counts = match.Groups[3];
var units = match.Groups[4];
for (int i = 0; i < signs.Captures.Count; i++)
{
string sign = signs.Captures[i].Value;
int count = int.Parse(counts.Captures[i].Value);
string unit = units.Captures[i].Value;
if (sign == "-") count *= -1;
switch (unit)
{
case "Y": epoch = epoch.AddYears(count); break;
case "M": epoch = epoch.AddMonths(count); break;
case "D": epoch = epoch.AddDays(count); break;
}
}
}
else
{
throw new FormatException(
"The specified expression was not a valid date expression.");
}
return epoch;
}
您可以使用 DateTime 和 TimeSpan 的组合来完成所有这些操作。您可以在http://dotnetperls.com/timespan找到一些很好的示例
从您的示例中: DateTime EstimatedArrivalDate = DateTime.Now.AddDays(3);