1

Considering the following situation:

let record = "2020-04-01 13:33 PM UTC";
var local_date = moment(new Date(record)).format("MMM Do, YYYY h:mm A");

Above code returns invalid date.

But for the following situation:

let record = "2020-04-01 2:33 AM UTC";
var local_date = moment(new Date(record)).format("MMM Do, YYYY h:mm A");

it returns : Apr 1st, 2020 8:33 AM

Link to sandbox: https://codesandbox.io/s/happy-volhard-m1c7d

Any suggestions to solve this problem ?

3 Answers3

1

If the string you want to parse is not one of the formats supported by moment.js and you don't provide the format, it will use the built–in parser instead. You will have a message in the console warning you that is a bad idea (because it is, see Why does Date.parse give incorrect results?).

When you have any unsupported format string, you must provide the format, e.g.

let s = "2020-04-01 13:33 PM UTC";

// Provide the input format when parsing
let d = moment(s, 'YYYY-MM-DD HH:mm A UTC');

// Provide the output format when formatting
console.log(d.format('MMM Do, YYYY h:mm A'));

// If the date is to be treated as UTC, use .utc
console.log(d.utc().format('MMM Do, YYYY h:mm A'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

BTW, when using 24 hour time, using AM and PM is redundant (and possibly confusing).

RobG
  • 142,382
  • 31
  • 172
  • 209
0

The UTC that you're providing is not correct, Either change the MMM Do, YYYY h:mm A to MMM Do, YYYY hh:mm A or change the time first to 12 hr format. The format is expecting 01,11,24 etc.

Prajil Shrestha
  • 124
  • 1
  • 9
0
 moment(record, "YYYY-MM-DDHH:mmZ").format("MMMM Do YYYY, H:mm");