0

This is my code. I make it random but the timezone is always in there and i dont know how to disappear the timezone, can someone help me with this I'am beginner in this thanks

var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD

function formatDate(date) {
  const year = date.getFullYear();
  /* getMonth returns dates from 0, so add one */
  const month = date.getMonth() + 1;
  const day = date.getDate();
  
  return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}

var getDateArray = function(start, end) {

  return new Date(
    start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
  );

}
var dateArr = getDateArray(startDate, endDate);


console.log(dateArr);
  • When you create a new date object using new Date(), it contains the timezone. If you just the date string without timezone then you will have to format it. Perhaps use own own format function : `var dateArr = formatDate(getDateArray(startDate, endDate))`; – subodhkalika Jul 15 '22 at 03:54
  • https://stackoverflow.com/questions/17545708/parse-date-without-timezone-javascript. If you dont care about the offset or any problem and just want the date you could do const dateOnly = dateArray.split('T')[0] – Simran Birla Jul 15 '22 at 04:00

1 Answers1

1

If you call the formatDate function you have in your code, I believe that will get rid of the timezone information.

var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD

function formatDate(date) {
  const year = date.getFullYear();
  /* getMonth returns dates from 0, so add one */
  const month = date.getMonth() + 1;
  const day = date.getDate();
  
  return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}

var getDateArray = function(start, end) {

  return formatDate(new Date(
    start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
  ));

}
var dateArr = getDateArray(startDate, endDate);


console.log(dateArr);

All I did here was add a call to your formatDate function within the getDateArray function so that now the return of the getDateArray will no longer contain timezone information.

Naren Murali
  • 19,250
  • 3
  • 27
  • 54
Josh S
  • 23
  • 4