clar1k
clar1k
TTCTheo's Typesafe Cult
Created by clar1k on 1/21/2025 in #questions
Weird timestamp behaviour or i don't understand something..
Hi! Can you help me with an issue?
We have a countdown on this page: https://dashboard.babywhale.meme/, counting down to January 23, 17:00 UTC.
The problem is with different time zones: the time difference varies between them.
How can I implement this properly? Here’s what I’ve written, but it doesn’t work correctly for other time zones:
"use client";
import { useState, useEffect } from "react";
import dayjs, { Dayjs } from "dayjs";
import utc from "dayjs/plugin/utc";

dayjs.extend(utc);

interface TimeLeft {
days: number;
hours: number;
minutes: number;
seconds: number;
}

export function useCountdown(targetDate: Dayjs) {
const [timeLeft, setTimeLeft] = useState<TimeLeft>({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});

useEffect(() => {
const calculateTimeLeft = () => {
const now = dayjs(); // Get current time in UTC
const targetUtc = targetDate.utc(); // Ensure target date is in UTC
const difference = targetUtc.diff(now);

if (difference <= 0) {
setTimeLeft({ days: 0, hours: 0, minutes: 0, seconds: 0 });
return;
}

const totalSeconds = Math.floor(difference / 1000);
const days = Math.floor(totalSeconds / (3600 * 24));
const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;

setTimeLeft({
days,
hours,
minutes,
seconds,
});
};

calculateTimeLeft();

const timer = setInterval(calculateTimeLeft, 1000);

return () => clearInterval(timer);
}, [targetDate]);

return timeLeft;
}
"use client";
import { useState, useEffect } from "react";
import dayjs, { Dayjs } from "dayjs";
import utc from "dayjs/plugin/utc";

dayjs.extend(utc);

interface TimeLeft {
days: number;
hours: number;
minutes: number;
seconds: number;
}

export function useCountdown(targetDate: Dayjs) {
const [timeLeft, setTimeLeft] = useState<TimeLeft>({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});

useEffect(() => {
const calculateTimeLeft = () => {
const now = dayjs(); // Get current time in UTC
const targetUtc = targetDate.utc(); // Ensure target date is in UTC
const difference = targetUtc.diff(now);

if (difference <= 0) {
setTimeLeft({ days: 0, hours: 0, minutes: 0, seconds: 0 });
return;
}

const totalSeconds = Math.floor(difference / 1000);
const days = Math.floor(totalSeconds / (3600 * 24));
const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;

setTimeLeft({
days,
hours,
minutes,
seconds,
});
};

calculateTimeLeft();

const timer = setInterval(calculateTimeLeft, 1000);

return () => clearInterval(timer);
}, [targetDate]);

return timeLeft;
}
4 replies