Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Created February 10, 2024 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/4b30a8f62aad3f77776973d7f9f4aad2 to your computer and use it in GitHub Desktop.
Save sturmenta/4b30a8f62aad3f77776973d7f9f4aad2 to your computer and use it in GitHub Desktop.
show remaining time in react (59:59 - 00:00) with dayjs
// initialize this config when the app start as importing the file (import "@/config/dayjs-config")
import dayjs from "dayjs"
import duration from "dayjs/plugin/duration"
import utc from "dayjs/plugin/utc"
dayjs.extend(duration)
dayjs.extend(utc)
import dayjs from "dayjs"
import { useEffect, useState } from "react"
import { Text } from "react-native"
// NOTE:
// show max 59:59 time remaining
// show 00:00 when time is expired
export const RemainingTime = ({ expired_time }: { expired_time: string }) => {
const [time, setTime] = useState("00:00")
const _setTime = () => {
const diff = dayjs(expired_time).diff(dayjs())
if (diff < 0) return setTime("00:00")
const dur = dayjs.duration(diff)
const remaining = dayjs.utc(dur.asMilliseconds()).format("mm:ss")
setTime(remaining)
}
useEffect(() => {
_setTime() // don't wait 1 second to show the time
const setTimeInterval = setInterval(_setTime, 1000)
return () => {
clearInterval(setTimeInterval)
}
}, [])
return <Text>{time}</Text>
}
// why use utc? -> https://github.com/iamkun/dayjs/issues/641#issuecomment-643924034
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment