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.
fetch(`https://www.some-url/apps/bookings/calendar-json.php?todayDate=${year}-${month}-${day}`)
.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?
CodePudding user response:
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()
.