如何获取时差矩js?

How to get time difference moment js?

我想要客户端和服务器之间的时间差。我使用 diff 但出现此错误

 "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>

您创建的日期无效,应该是这样的:

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

.format returns 字符串而不是日期

那么你还有一个额外的问题,即 Damnmarkshavn 不在时区包中,除非你将 JSON 添加到你的项目

所以可能需要根据

添加

https://momentjs.com/timezone/docs/#/data-loading/

但是我在 JSON 中看到了它 "America/Danmarkshavn|LMT -03 -02 GMT|1e.E 30 20 0|01212121212121212121212121212121213|-2a5WJ.k 2z5fJ.k 19U0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 DC0|8"

如果你想知道区别,你需要这段改编自Use moment and moment timezone to properly implement diff

的代码

否则你会得到 0、1 或 -1 毫秒的差异

现在这里是 7:55am,格陵兰岛是 05:55,例如格林威治标准时间 -2 小时 - 这里是 -3 小时,这是我从这段代码中得到的

const date = moment()
console.log(date)
moment.tz.add("America/Danmarkshavn|LMT -03 -02 GMT|1e.E 30 20 0|01212121212121212121212121212121213|-2a5WJ.k 2z5fJ.k 19U0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 DC0|8");

const diff = moment.tz("07:55", "HH:mm","America/Danmarkshavn").diff(date); // replace 07:55 with your server time
console.log(moment(diff).format("HH.mm"))
<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>