Home > Software design >  JS create a new date based on different interval types
JS create a new date based on different interval types

Time:04-17

I am trying to make JavaScript that creates a new date based on a certain interval that could be either years, months, days or hours. I would like to create a new date with time depending on interval type. I don't really know how to start.

    var startDate = 2022-04-19T10:00:00.000Z
    var interval = 10
    var intervalType = "days" // could be Months, Days, Hours

CodePudding user response:

You can try this:

var startDate = "2022-04-19T10:00:00.000Z";
function parseISOString(s) {
  var b = s.split(/\D /);
  return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
const date = parseISOString(startDate).getTime();
var interval = 10;
var intervalType = "days" // could be Months, Days, Hours
const newDate = (function () {
   if (intervalType == "days") {
      return new Date((interval * 86400000)   date).toISOString();
   } else if (intervalType == "months") {
      return new Date((interval * 86400000 * 30) date).toISOString(); // Taking 1 month = 30 days
   } else {
      return new Date((interval * 3600000)   date).toISOString();
   }
})()
console.log(newDate);

CodePudding user response:

From your explanation above, you want to be able to set interval and interval type and then generate date distance from start date.

var startDate = "2022-04-19T10:00:00.000Z";
var interval = 5;
var newDate = new Date(startDate);
var intervalType = "hours"; // could be Months, Days, Hours

function generateInterval() {
  if (intervalType === "hours") {
    //if your GMT is  1 then you have to remove 1 from the hours unless your startDate is not constant
    const hour = new Date(startDate).getHours();
    const date = newDate.setHours(hour   interval);
    console.log(new Date(date));
  } else if (intervalType === "days") {
    const day = new Date(startDate).getDate();
    const date = newDate.setDate(day   interval);
    console.log(new Date(date));
  } else if (intervalType === "months") {
    const month = new Date(startDate).getMonth();
    const date = newDate.setMonth(month   interval);
    console.log(new Date(date));
  }
}

generateInterval()

  • Related