Help summing up a TV watched times by date in dataviewjs

What I’m trying to do

I am trying to create an array that has date and sum of minutes of TV watched on that date using dataviewjs (I will pass this array to Heatmap Calendar plugin)

The frontmatter of my files has the following (among other things)

---
watched: 2024-03-21 08:01:00
length: 61
---

What I have done so far

The following works but I can’t figure out how to create a sum of lengths of all the shows watched on that particular day (this gives just one from that day)

```dataviewjs
dv.span("Lenght of TV watched")

const calendarData = {
    entries: []
}

for(let page of dv.pages('"Movies and TV Shows"').where(p=>p.length)){

    const date = new Date(page.watched);
    const yyyy = date.getFullYear();
    let mm = date.getMonth() + 1; // Months start at 0!
    let dd = date.getDate();
    if (dd < 10) dd = '0' + dd;
    if (mm < 10) mm = '0' + mm;
    const formattedDate = yyyy + "-" + mm + '-' + dd;
	
    calendarData.entries.push({
        date: formattedDate,
        intensity: page.length
    })
       
}

renderHeatmapCalendar(this.container, calendarData)

Any help in fixing this code will be greatly appreciated.

Solved it with the following code

dv.span("Length of TV watched");

const calendarData = {
    entries: []
};

const lengthByDate = {};

// Loop through all pages with a 'length' property
for (let page of dv.pages('"Movies and TV Shows"').where(p => p.length)) {
    const date = new Date(page.watched);
    const yyyy = date.getFullYear();
    let mm = date.getMonth() + 1;
    let dd = date.getDate();
    if (dd < 10) dd = '0' + dd;
    if (mm < 10) mm = '0' + mm;
    const formattedDate = yyyy + "-" + mm + '-' + dd;

    // Add the length to the corresponding date
    if (!lengthByDate[formattedDate]) {
        lengthByDate[formattedDate] = 0;
    }
    lengthByDate[formattedDate] += page.length;
}

// Convert the accumulated lengths into the format needed for the heatmap
for (const [date, totalLength] of Object.entries(lengthByDate)) {
    calendarData.entries.push({
        date: date,
        intensity: totalLength
    });
}

renderHeatmapCalendar(this.container, calendarData);

Just because it came up recently and it seems not everyone is aware, you can use human-readable durations in your properties, and Dataview can still sum them up:

image

And the code to sum them up and display the total time is very straightforward:

```dataviewjs
let totalDuration = Duration.fromMillis(0) // create a new duration

totalDuration = totalDuration.plus(dv.current().tv_time_1)
totalDuration = totalDuration.plus(dv.current().tv_time_2)

dv.paragraph('Total time: ' + totalDuration.toFormat("h 'hours and' m 'minutes.'"))
dv.paragraph('Total minutes: ' + totalDuration.as('minutes'))
```
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.