Search code examples
javascriptmomentjsutc

How to format datetime without timezone (Z) using moment.js with AM/PM


I am converting DateTime to display YYYY-MM-DD hh: mm a format using moemntjs in my web application but I do not want momentjs to convert or consider timezone.

This is my date 2018-12-21T15:58:39.35-05:00 returned as part of API and need to display date without (-05:00) in YYYY-MM-DD hh: mm a format.

I am currently doing a workaround as below

var date1 = '2018-12-21T15:58:39.35-05:00'
var fmtDate = moment.utc(date1).zone("-05:00").format('YYYY-MM-DD hh:mm a');

$('#output').append(fmtDate);

Fiddle Link

Input: '2018-12-21T15:58:39.35-05:00' Expected Output: '03:58 pm'
But I don't want to hardcode zone (-05:00) and moment.js should exclude that in formatting.


Solution

  • utcOffset is what you need:

    var date1 = '2018-12-21T15:58:39.35-05:00'
    var m = moment(date1).utcOffset(date1);
    var fmtDate = m.format('YYYY-MM-DD hh:mm a');
    
    $('#output').append(fmtDate); // result is as you expected: 2018-12-21 03:58 pm
    

    here is the example: https://jsfiddle.net/73pa1qkz/9/