Is there a way to convert a string containing a date calculation, such as "now + 1 day", into a date object?

Currently, my team is utilizing Cucumber to define our test cases within string-based feature files. Our integration tests are executed against a wiremock stub that contains date calculations such as: "{{now offset='+15 minutes'}}"

I am seeking to verify the accuracy of the date and time retrieved from the wiremock stub, ensure the correct display of this information, and confirm that the table is correctly ordered based on these dates and times.

Presently, we have our custom implementation for obtaining the current date with an offset of +/- X days. However, this method employs regex and only supports day adjustments. While I could enhance this solution to include minute calculations, I would prefer to utilize a library or standardized code snippet capable of parsing all types of date calculations. Unfortunately, my search for such a tool has been fruitless thus far, and I would appreciate any recommendations to tackle this challenge.

To provide context, here is the function currently utilized:

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);
  });
}

In our cucumber tests, it is applied as follows, adjusting the current date by subtracting the specified number of days:

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

Answer №1

When it comes to date calculations, there isn't a set standard to follow which may make it difficult to find a pre-existing library for this purpose. However, you can utilize certain parts of existing standards to simplify your custom date calculations.

Instead of creating your own format from scratch, consider using the ISO-8601 duration format. This way, you can leverage available libraries to interpret the duration format and integrate it with the current time.

Here are some examples:

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

Answer №2

Consider utilizing DayJs from DayJS. It is a lightweight alternative with enhanced features compared to momentjs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Receiving updates on the status of a spawned child process in Node.js

Currently, I'm running the npm install -g create-react-app command from a JavaScript script and I am looking to extract the real-time progress information during the package installation process. Here is an example of what I aim to capture: https://i ...

Creating a vibrant and mesmerizing inward spiraling rainbow of colors on canvas using JavaScript

After coming across an image that caught my eye, I was inspired to recreate it using canvas: https://i.stack.imgur.com/fqk3m.png I've attempted drawing arcs starting from the center of the screen, but I'm struggling with getting their paths acc ...

Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is: KM driven per year * Avg KM/100L / Price of fuel I have managed to display each slider's individual values, but I am uncertain about how to show t ...

Tips for retrieving the clicked word in JavaScript

Is it possible to retrieve the word that was right-clicked on along with its x, y coordinates? I attempted the following code:document.onclick=getTextOnClick; function getTextOnClick(e) { console.log(e); if (window.getSelection) { txt = wi ...

VueJS does not support certain characters in its JavaScript replace function

In my current situation, I am utilizing the replace method in the following manner: <code v-html="'/<try>/'.replace(/(?:\r\n|\r|\n)/g, 'testing')"></code> As I work with a longer string t ...

Combining all code in Electron using Typescript

I am currently working on developing a web application using Electron written in Typescript and I am facing some challenges during the building process. Specifically, I am unsure of how to properly combine the commands tsc (used to convert my .ts file to ...

Error code TS7053 occurs when an element implicitly has an 'any' type because a string expression cannot be used to index an empty object

I have implemented a code snippet that sorts items into groups based on their first character. For example, if the array of item looks like this: {name: 'Foo'} {name: 'Bar'} {name: 'Baz'} The expected result should be: B: ...

Transferring Parameters to EJS Template in Node.js

Hey guys, I'm having an issue with rendering a MongoDB record in my .ejs file. Strangely, when I console.log the variable before the end of my route, I get the expected value. However, it becomes undefined in the .ejs file. Here is the code snippet: ...

Using indented, multi-line logging in a NodeJS environment can help to

I'm looking for a way to display objects that have been printed with JSON.stringify() in the console, specifically within the context of a Mocha test suite output. While my tests are running, I want the object log lines to be indented further to the ...

What is the best way to conduct tests on React components' methods and ensure they are integrated into my Istanbul coverage report

Is there a way to test the methods of react components and include them in my Istanbul test coverage? Edit: I'm using enzyme. Just wanted to mention that. Take, for instance, this component: class SearchFormContainer extends Component { static h ...

Reorganize the JSON data to match the specified format

{ "EUR": { "Description": "", "Bid": "1.1222", "Region": "", "Bid1": "1.1283", "CurrencyCode": "EUR", "FeedSource": "1", "Ask": "1.1226", "ProviderName": "TEST 1", "Low": "1.1195", ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

A fresh checkbox was added to the page using Jquery Switchery to disable it

I'm having trouble disabling the Switchery checkbox. When I try to disable it, another Switchery checkbox appears on the page along with the one I previously defined: <div class="form-group"> <label class="col-md-2"> ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...

Tips for customizing the appearance of a Link component while it is the active page in Next.js

I'm seeking advice on how to style an anchor component differently when it is active on a page. Here's the code I have so far: import Link from 'next/link'; import styled from 'styled-components'; const NavStyle = styled.nav` ...

Find the sum of values in an array of objects if they are identical

[{ingName: "milk", quantity: "1.5", unit: "cups"}, {ingName: "sugar", quantity: "0.25", unit: "cups"}, {ingName: "vanilla extract", quantity: "1.0", unit: "tsp&quo ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

Tips for creating a countdown timer from scratch without relying on a plugin

Looking at this image, it is clear that jQuery can be used. However, I am wondering if there is a way to create a countdown timer without relying on plugins. Can anyone offer some guidance? ...

Issue with Ajax submit button failing to pass ID

I am encountering an issue while trying to update data using bootstrap modal. When the CGridView selectionChanged event is triggered, it should call a function to display a modal dialog form and populate the form with the selected data. Below is my CGrid ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...