Solution with plain javascript:(使用纯JavaScript的解决方案:)
- Get the clients time zone offset(获取客户的时区偏移量)
- Calculate the diff between
client offset
and "Australian/Brisbane" offset
(计算client offset
与"Australian/Brisbane" offset
之间的差异)
- Calculate time left by
targetDate - currentDate - offsetDiff
(计算targetDate - currentDate - offsetDiff
)
- Format the result to display it(格式化结果以显示它)
Example:(例:)
const minToMS = min => min * 60 * 1000
const getCountDownFromMS = diff => {
const milliseconds = diff % 1000
diff = (diff - milliseconds) / 1000
const seconds = diff % 60
diff = (diff - seconds) / 60
const minutes = diff % 60
diff = (diff - minutes) / 60
const hours = diff % 24
diff = (diff - hours) / 24
const days = diff
return {
days,
hours,
minutes,
seconds,
milliseconds
}
}
const targetDate = new Date('2019-11-29 00:00:00')
// Getting offset with getTimezoneOffset is not reliable, using a database to get time zone offset is needed, like IANA Time Zone Database.
// moment.js internally uses IANA db
const tzOffset = targetDate.getTimezoneOffset() // Client browsers timezone offset in minutes
const target_tzOffset = -600 // Australia Brisbane timezone offset in minutes
const offset = minToMS(tzOffset - target_tzOffset)
const msLeft = targetDate - new Date() - offset
const result = getCountDownFromMS(msLeft)
You should also check moment.js as it has many useful features.(您还应该检查一下moment.js,因为它具有许多有用的功能。)
Example with moment.js:(使用moment.js的示例:)
const now = moment()
const target = moment.tz('2019-11-29 00:00:00', 'Australia/Brisbane')
const result = moment.duration(target.diff(now))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…