我正在尝试创建一个具有GMT结束日期和独立于时区的开始日期的计时器,这样任何用户都可以准确地跟踪倒计时。
const currentDate = new Date();
const gmt = new Date(
currentDate.getTime() + currentDate.getTimezoneOffset() * 60000
);
const endTime = 1666818000;
const [time, setTime] = useState(0);
useEffect(() => {
const timer = setTimeout(() => {
setTime(SecondsToTime(endTime - Math.floor(gmt / 1000)));
}, 1000);
return () => clearTimeout(timer);
});
getTime+timezoneOffset不起作用。
let now = new Date();
let nowUTC = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
也不起作用
您可以使用日期fns-tz将时间格式化为UTC。
他们文档中的示例:
import { zonedTimeToUtc } from 'date-fns-tz'
const date = getDatePickerValue() // e.g. 2014-06-25 10:00:00 (picked in any time zone)
const timeZone = getTimeZoneValue() // e.g. America/Los_Angeles
const utcDate = zonedTimeToUtc(date, timeZone) // In June 10am in Los Angeles is 5pm UTC