How can I set a date in an API URL query string

I am using the fetch API (unfetch npm polyfil) to retrieve some JSON data from a server.

The fetch call looks something like this and relies on the current date in the query string to return the current date's data.

  .then(r => r.json)... ``

The data returned is essentially showing the available bookings for the current date as set in the API url. I want to have a set of controls that allows the user to increment or decrement the date to show the bookings for that particular date. To do this I was going to get the current date in ISO format (like below) then split up the year, month, day into a de-structured array and use those in the API query string. -

const date = new Date();
const isoFormat = date.toISOString();
const currentDate = isoFormat.substr(0,10);

From there, is it then possible to manipulate the date variables via increment/decrement to get previous or next days dates in the API URL? I suppose a bit like a counter.

Or is there a better way that already exists for handling this? A package like moment.js or something?

1 answer

  • answered 2021-09-27 15:48 Zouhair Dre

    If you want to increment/decrement the Date, it is easier to use a separate variable for, year, month and day :

    let today = new Date();
    let yyyy = today.getFullYear();
    let mm = today.getMonth()+1; // getMonth() is zero-based
    let dd  = today.getDate();

    Or you can use directly the Date Object,

    let offsetByDays = (24*60*60*1000) * 2; //2 days
    let date= new Date();
    date.setTime(date.getTime() - offsetByDays );
    let formattedDate = date.toISOString().slice(0,10);

    For moment.js see : momentJS date string add 5 days

    NB: You have too take in consideration the timezone when using .toISOString().

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum