Home > Blockchain >  Time formatting issues with Moment.JS
Time formatting issues with Moment.JS

Time:02-12

I have some DB objects coming back from my server as so:

client_id: 24
created_at: "2022-02-11 17:41:39.330443"
id: 22
report: "sfsf"
report_category: "Client Assigned"
volunteer_id: 23


client_id: 24
created_at: "2022-02-11 17:43:04.837869"
id: 23
report: "one more"
report_category: "Client Assigned"
volunteer_id: 23

In my React code I am trying to apply formatting with moment to the created_at field:

{moment(comment.createdAt).format('DD/MM/YY, h:mm a')}

which returns something like:

11/02/22, 12:46 pm

For all the objects the time just seems to default to the current time it is right now and not the time in the created_at field. All the entries show 12:46 pm. Any advice on this issue?

CodePudding user response:

Your object call looks to be incorrect and may be defaulting to current time because in your sample object:

{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}

your code calls createdAt when you likely need created_at:

moment(comment.created_at).format('DD/MM/YY, h:mm a')

sample test run as string:

const out = document.getElementById('output')
const testDate = "2022-02-11 17:41:39.330443"
const momentCode = moment(testDate).format('DD/MM/YY, h:mm a')
out.innerText = momentCode
<p id="output"></p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

CodePudding user response:

I was thinking maybe the formatting is errored and it just defaults to current time if so. What does the 'a' do at the end for the format. Maybe try something like this "HH:mm:ss"

  • Related