简体   繁体   中英

Find all missing dates in an JSON object in Javascript / Typescript

In my application I am in need to show missing date range. I tried to get the first and last date but got struck to proceed further. when I tried, I got only the first missing date but the expected output is to display all missing dates from the start date to end date.

https://jsfiddle.net/bgef59x2/3/

https://stackblitz.com/edit/ionic-rknmsc?file=pages%2Fhome%2Fhome.ts

var data={
"dataObj"=[
{"custom_date":"2020-04-13"},
{"custom_date":"2020-04-19"},
{"custom_date":"2020-04-20"},
{"custom_date":"2020-04-21"}
]}

my startDate would be "2020-04-13" and enddate would be "2020-04-21" Expected output:

const result =["2020-04-14","2020-04-15","2020-04-16","2020-04-17","2020-04-18"]

Guide me to achieve the expected result in JavaScript/ Typescript. I have not included momentJs in my application.

Web, just only create a llop from date to date, check if is in the array a push in an array

missingDates:string[]=[]
const missingDates: string[] = [];

const from = new Date(this.data[0].custom_date);
const to = new Date(this.data[this.data.length - 1].custom_date);
for (let fecha = from;fecha < to;fecha = new Date(fecha.getTime() + 24 * 60 * 60 * 1000)) {
  const date =fecha.getFullYear() +"-" +
    ("00" + (fecha.getMonth() + 1)).slice(-2) +"-" +
    ("00" + fecha.getDate()).slice(-2);

  if (!this.data.find(x => x.custom_date == date)) missingDates.push(date);
}
console.log(missingDates)

Better solution exists, but this script excludes dates as expected:

 var dataObj = [ {"custom_date":"2020-04-13"}, {"custom_date":"2020-04-19"}, {"custom_date":"2020-04-20"}, {"custom_date":"2020-04-21"} ]; var dates = dataObj.map(d => d.custom_date) console.log(getMissingDates(dates)); function getMissingDates(dates) { var datesParsed= dates.map(d => new Date(d)).sort() var allExpectedDates = []; var missingDates = []; var from = datesParsed[0]; var to = datesParsed[datesParsed.length - 1]; var current = from; while (current <= to) { allExpectedDates.push(formatDate(current)); current.setDate(current.getDate() + 1); } return allExpectedDates.filter(el => { return dates.indexOf(el) === -1; }); } // from https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd: function formatDate(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM