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

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Using regular expressions to extract substrings from URL

I have different URL routes, such as var url = '/product' and '/product/create'. Is there a way to use Regex in order to extract only the route name like 'product'? ...

I can't seem to establish a connection with my MongoDB Atlas cluster. I encountered the MongooseError, which is as follows:

Error [MongooseError]: The uri parameter for the openUri() method needs to be a string but is currently set as "undefined". Please ensure that the first parameter for mongoose.connect() or mongoose.createConnection() is a valid string. const express = r ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

What steps do I need to take to convert a view from a three.js camera and scene to a bcf cameraview?

I am attempting to convert a ifc.js viewer file into a bcf format. The ifc.js viewer utilizes a three.js webglrenderer along with a camera and scene setup. Shown below is an example: https://i.sstatic.net/oTphJ.png https://i.sstatic.net/8Dtag.png I would ...

I possess a function that can retrieve the key of an Object, but now I am faced with the task of accessing the actual Object using this value in JavaScript

This is my first time seeking advice on a technical issue. I'm currently working with the following function: export function sendRequest<T>(req: RawRequest, options) { const start = Date.now(); const reqOptions: CoreOptions = { ...

Ways to ensure a function is only triggered once using onmouseover

I'm fairly new to JavaScript and I've been attempting to create a function that only runs once. Here's the logo I've been trying to animate: <img src="img/logot2.png" id="logoutjs" onmouseover="move()" ...

Oops! Next JS encountered an unhandled runtime error while trying to render the route. The

I keep receiving the error message Unhandled Runtime Error Error: Cancel rendering route Within my navBar, I have implemented the following function: const userData={ id:1, email: "", name: "", lastName: "", ...

Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match &apo ...

Please input only 0s and 1s into the designated field

How can I modify this code to only accept 0 and 1 in the input field, while also adding spaces after every 4 digits? Currently, it accepts all digits. I'm struggling with creating a pattern that restricts it to just 0 and 1. document.getElementById(&a ...

Implementing jQuery getScript in a Ruby on Rails 3 application

After watching a railscast tutorial on loading records through ajax when a link is clicked, I implemented the following javascript: $(function() { $("#dash_container th a").live("click", function() { $.getScript(this.href); return false; }); } ...

Angularjs - How come I am able to modify an object but not the list (ng-repeat) from a separate view?

After updating the customers object in the console, I noticed that the list (ng-repeat) is not reflecting the changes. What should I do? Interestingly, it works fine when I implement this function and view2.htm's HTML inside page.htm. HTML "page.htm" ...

What could be causing this minimal Angular - WebTorrent configuration to fail?

The setup appears to be quite straightforward. Check out the Webtorrent usage reference here This is how I have my setup: import WebTorrent from 'webtorrent'; @Component({ selector: 'app-root', standalone: true, template: `bla` ...

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...

The dynamic styles set by CSS/JavaScript are not being successfully implemented once the Ajax data is retrieved

I am currently coding in Zend Framework and facing an issue with the code provided below. Any suggestions for a solution would be appreciated. The following is my controller function that is being triggered via AJAX: public function fnshowinfoAction() { ...

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

Using optional arguments in my AngularJS controller.js

In my controller.js file for AngularJS, I have the following code snippet: app.controller('MetaDetailGroupList', ['$scope', '$http', function($scope, $http) { $http.get(Routing.generate('meta-detail-group-list&ap ...

Having trouble displaying results in Vue.js after making an API request?

I am facing challenges in displaying the results using vue.js. The data from my API (ASP.NET CORE) is being retrieved successfully, as shown in my vue dev tools on Google Chrome. However, I am encountering difficulties in rendering the results on the brows ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...