mpora
mpora

Reputation: 1479

moment js timeformat not producing the correct time

I have an API returning a date as follows:

2020-04-30T14:52:07.123

and I am trying to format it as follows:

$('.dateTime').text(moment(new Date("2020-04-30T14:52:07.123")).format("DD-MM-yyyy HH:mm:ss A"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>


<span class="dateTime"></span>

but I am not getting the right result. I get this:

"30-04-2020 00:00:00 AM"

Day, month and year are correct but the the hour, minutes and seconds are set to midnight.

Upvotes: 0

Views: 863

Answers (1)

VincenzoC
VincenzoC

Reputation: 31502

I think that the 00:00:00 is a side effect of new features included in moment 2.25.x version, if you run you code using previous version (e.g. 2.24.0), you will get 30-04-yyyy 14:52:07 AM.

The main issue with your code is that moment tokens are case sensitive (see format()), so you have to use uppercase YYYY to display 4 digit year instead of lowercase yyyyy.

Moreover, since your input string is in ISO 8601 recognized format you can directly use moment(String) and remove new Date().

Working example:

$('.dateTime').text(moment("2020-04-30T14:52:07.123").format("DD-MM-YYYY HH:mm:ss A"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment.js"></script>

<span class="dateTime"></span>

Upvotes: 1

Related Questions