Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
converting time to local timezone not working with moment.js in React

I am converting a timestamp on a DB object using moment:

{moment(comment.created_at).local(true).format('h:mm a')}

My time is outputting in UTC time because that is how it gets created in my DB. So I am seeing '6:45 PM' for example, when I want to see the time in MY timezone (EST) or the user's relative timezone. According to the moment docs local() will convert to your current timezone? Calling the local() method as shown in my code aboven does not change the time zone. Am I using this incorrectly?

My DB object

{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Your database is storing the date without an offset indicator. This means that moment cannot automatically determine the timezone. As per the documentation on parsing dates:

moment(...) is local mode. Ambiguous input (without offset) is assumed to be local time. Unambiguous input (with offset) is adjusted to local time. * moment.utc(...) is utc mode. Ambiguous input is assumed to be UTC.

So if you know your input is UTC and you know it won't have an offset indicator, use moment.utc() instead of moment().

Furthermore, you don't want to use local(true), since passing in "true" will only change the timezone on the object without changing the time (see the documentation). So you're left with:

{moment.utc(comment.created_at).local().format('h:mm a')}
about 4 years ago · Juan Pablo Isaza Report

0

I converted your DB timestamp into ISO format and then passed into your implementation

let t = "2022-02-11 17:41:39.330443"

let utcISOTimestamp = moment.utc(t).toDate()
console.log(utcISOTimestamp)

//let res = moment(utcISOTimestamp).local(true).format('h:mm a');
let res = moment(moment.utc(t).toDate()).local(true).format('h:mm a');

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

about 4 years ago · Juan Pablo Isaza Report

0

Try using:

moment.utc('2022-02-11 17:41:39').local().format('YYYY-MM-DD HH:mm:ss')
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!