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
}
CodePudding user response:
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')}
CodePudding user response:
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>
CodePudding user response:
Try using:
moment.utc('2022-02-11 17:41:39').local().format('YYYY-MM-DD HH:mm:ss')