I have a code that allows me to fetch xml data from a url and I am trying to figure out how to display all the date data for each specific month. I manage to split the date (dd/mm/yyyy format) by splitting with("/") method. How do i get all the date data from each specific month?
console.log("Fetching from URL: ", currenturl);
fetch(currenturl)
.then(response => response.text())
.then(data => {
const parser = new DOMParser();
const xml = parser.parseFromString(data, "application/xml");
var getdate = xml.getElementsByTagName("date");
var amountOfdate = getdate.length;
//display the total amount of date element in the xml file.
console.log(amountOfdate);
for (let i = 0; i < amountOfdate; i){
var getstringdate = getdate[i].childNodes[0].nodeValue;
var arrmonth = getstringdate.split("/");
var getmonth = parseInt(arrmonth[1]);
}
}
console.log("stop");
})
.catch(console.error);
Xml example(i have a big amount of data)
<datedata>
<month>
<date>01/01/2007</date>
</month>
<month>
<date>01/01/2007</date>
</month>
<month>
<date>01/02/2007</date>
</month>
</datedata>
How to get all the data that has the getmonth value of 1?
result in console.log :
01/01/2007
01/01/2007
CodePudding user response:
const data = `
<datedata>
<month>
<date>01/01/2007</date>
</month>
<month>
<date>01/01/2007</date>
</month>
<month>
<date>01/02/2007</date>
</month>
</datedata>`;
const parser = new DOMParser();
const xml = parser.parseFromString(data, "application/xml");
const dates = xml.getElementsByTagName("date");
const result = Array.from(dates)
.map(date => date.childNodes[0].nodeValue)
.filter(dateString => {
const [day, month, year] = dateString.split('/');
return month === '01'
})
console.log(result);
CodePudding user response:
If the dates stay the same in this format you can check if the date contains the month as string
const month = '01'
let dates = getDate.filter(date => {
return date.includes(`/${month}/`)
})