Search code examples
javascripttimemomentjsmoment-timezone

How to get time difference moment js?


I want time difference between client and server. I used diff but getting this error

 "TypeError: date.diff is not a function"

const date = moment(new Date()).format()
const server = moment.tz("America/Danmarkshavn")
console.log(date.diff(server))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone.min.js"></script>


Solution

  • Your created dates are invalid it should be something like this :

    const date1 = moment() //Gives you current date and time
    var date2 = moment("2021/04/17") //Creates a date from the given string
    date1.diff(date2,"days") //returns the difference between these 2 dates in days