How to calculate a day difference between two dates (dataviewjs)

Hello,

I am a beginner in Obsidian, the question is simple (I solved more complicated stuff by reading the forum), but I didn’t find a way to solve it.

Thanks in advance!

What I’m trying to do

Calculate a day difference between two dates (dataviewjs)

Things I have tried

In dataviewjs block->

const xStartDate= moment(Date.now())
const xEndDate = moment(Date.now()).endOf(‘week’)

//Format is working
dv.span(“Week: " + xStartDate.format(‘dd DD.MM.yyyy’) + " bis " + xEndDate.format(‘dd DD.MM.yyyy’)+”")

//Difference is a large number, which has to be converted into days
dv.paragraph(“-Difference between startOf and endOf week " + (xEndDate - xStartDate))
dv.paragraph(”-Difference between startOf and endOf week " + (new Date(xEndDate) - new Date(xStartDate)))

//I tried with .days, but the result is undefined
dv.paragraph("-Difference in days between startOf and endOf week " + (new Date(xEndDate) - new Date(xStartDate)).days)

Personally, it may be more optimal, but I calculate the difference in days like this :

dv.paragraph("-Difference in days between startOf and endOf week " + Math.floor((xEndDate - xStartDate) / (24 * 60 * 60 * 1000)));

Thanks, I will use your approach too :slight_smile:

Since you’re already using moment.js dates, you could go all the way and use: xEndDate.diff(xStartDate, 'days') to show the day difference between those dates. For more information see thread on StackOverflow.

1 Like

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