如何将带有日期计算(如 now + 1 天)的字符串解析为日期对象?

How can I parse a string with a date calculation like now + 1 days into a date object?

我目前正在使用 Cucumber 在基于字符串的功能文件中定义我们的测试用例。集成测试将 运行 针对具有日期计算的 wiremock 存根,例如:“{{now offset='+15 minutes'}}”

我想验证我从线控存根获取的日期和时间是否正确显示,日期和时间是否正确,table 是否根据该日期和时间正确排序.

我们目前有自己的实现,现在需要 +/- X 天。这使用了一些正则表达式并且只支持几天。我可以扩展该代码并为其添加分钟,但我更愿意使用可以解析所有日期计算的库或标准化代码段。我一直没能找到它,希望得到一些关于如何解决这个问题的建议。

为了让您了解我目前在做什么:

function stringReplaceNow(string) {
  var regex = /<now:([A-Z-]+):?((\+|-)([0-9]+))?>/gi;

  return string.replace(regex, function (match, format, shouldModify, modification, modAmount) {
    if (modification === '+') {
      return moment().add(modAmount, 'days').format(format);
    } else if (modification === '-') {
      return moment().subtract(modAmount, 'days').format(format);
    }
    return moment().format(format);
  });
}

在我们的黄瓜测试中,它是这样使用的,它将获取当前日期并相应地减去天数:

| Name             | Datetime            | State      |
| Johnson          | <now:DD-MM-YYYY:-2> | Processing |
| Minter           | <now:DD-MM-YYYY:-3> | Processing |
| Brown            | <now:DD-MM-YYYY:-5> | Done       |

尝试使用 DayJs。它重量轻,功能比 momentjs 多。

日期计算没有标准,所以我怀疑您是否会找到它的库。但是,您可以使用部分现有标准来简化自定义日期计算。

在这种情况下,与其开发自己的格式,不如考虑使用 ISO-8601 时长格式。然后,您可以使用现有库来解析持续时间格式并将其添加到当前时间。

示例:

"PT20.345S" -- parses as "20.345 seconds"
"PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)
"PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)
"P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
"P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"
"PT-6H3M"    -- parses as "-6 hours and +3 minutes"
"-PT6H3M"    -- parses as "-6 hours and -3 minutes"
"-PT-6H+3M"  -- parses as "+6 hours and -3 minutes"