1

I have a UTC timestamp coming down from the server side. It's a static timestamp (for example: 11:30) I want to convert 11:30 to users local timezone.

I did this:

const SessionStartTime = () => {
    const startTime = moment.sessionStartTime
    const convertTime = moment.utc(startTime).toDate()
    const localTime = moment(convertTime)


    console.log(localTime)
    
    return <span>{new Date(startTime)}</span>
}

which converts the time to clients REAL-TIME which is not what I'm looking for. Any tips? edit:

After reading the docs I came up with this

const SessionStartTime = () => {
    const dateFormat = "HH:mm"
    const startTime = sessionStartTime
    const localTime = startTime.local()

    return <span>{localTime.format(dateFormat)}</span>
}

but it doesn't do anything.

UnluckyLAD
  • 169
  • 2
  • 18
  • If you already get a UTC timestamp, you can simply use `startTime.toLocaleTimeString()` to get the local time. There are some answer for these https://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time?rq=1 – kunquan Feb 25 '21 at 13:12
  • "startTime.toLocaleTimeString() is not a function" – UnluckyLAD Feb 25 '21 at 14:34
  • @kunquan forgot to add, startTime = UTC moment time. Maybe thats why toLocaleTimeString isnt working – UnluckyLAD Feb 25 '21 at 14:55
  • Does this answer your question https://stackoverflow.com/a/40407186/10675707? – Cursed Feb 25 '21 at 15:34
  • If all you have is "11:30", you can't perform any conversion to another time zone. You also need to know the *date*. Also, `moment.sessionStartTime` is not a thing. Show us the real code please. – Matt Johnson-Pint Feb 25 '21 at 16:11
  • @MattJohnos-Pint sessionStartTime is a variable that holds a UTC string that comes down from the server... – UnluckyLAD Feb 25 '21 at 16:13
  • @Matt Johnson-Pint besides, the 11:30 is clearly formatted "HH:mm" I should've stated that – UnluckyLAD Feb 25 '21 at 16:15
  • 1
    That's not what I mean. You may know the time is UTC, but without knowing which *date* it's from, you can't convert it to a time zone. Many time zones have different offsets from UTC depending on the date. For example, Eastern Time in the US uses UTC-5 during standard time and UTC-4 during daylight time. If you don't know the date, then you don't know which to apply during the conversion. In short, you need to have your server send both the date and the time, not just the time. – Matt Johnson-Pint Feb 25 '21 at 20:14

0 Answers0