45

I'm trying to use Moment.js to convert a Unix epoch time to a date and time. I'd also like to know how to have it formatted like below.

Tuesday, November 22, 2016 6:00 PM

danny
  • 461
  • 1
  • 4
  • 4

5 Answers5

98

You can initialize a moment object with the unix timestamp and then use the format() function to get your desired output.

const yourUnixEpochTime = 1687340912000;
// Create moment object from epoch and convert to format:
const formattedTime = moment(yourUnixEpochTime).format("dddd, MMMM Do, YYYY h:mm A")

$("#time").text(formattedTime);
<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.29.4/moment.min.js"></script>
<p id="time"></p>
Skully
  • 2,882
  • 3
  • 20
  • 31
manonthemat
  • 6,101
  • 1
  • 24
  • 49
32

From the Docs: Unix Timestamp

var day = moment.unix(1318781876); //seconds
var day = moment(1318781876406); //milliseconds

// and then:

console.log(day.format('dddd MMMM Do YYYY, h:mm:ss a'));

// "Sunday October 16th 2011, 9:17:56 am"
Keno
  • 3,694
  • 2
  • 21
  • 40
  • 1
    NOTE: The above is backwards, `moment.unix(timestamp)` is for seconds and `moment(timstamp)` is for milliseconds. Not the other way round as the answer describes (at least in the latest version of moment). – webnoob Nov 21 '17 at 11:28
  • 1
    @webnoob Thanks ! , changed it. – Keno Nov 21 '17 at 15:18
8

You can use .format('LLLL') for your requirement.

let result = moment(epoch).format('LLLL');

let epoch = 1562127342123;
let result = moment(epoch).format('LLLL');
console.log(result);
<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.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
5

You can use moment.unix(epochTime).

Jumpei Ogawa
  • 518
  • 1
  • 7
  • 18
0

Moment JS converts the Unix time to GMT equivalent. To convert it to EST which is 5 hours behind Coordinated Universal Time (UTC) : [momentjs]

const moment = require('moment');

console.log(moment(1580331903396).subtract(5, 'hours').format('MMMM Do, YYYY - h:mm:ss A '))

Refer working example here:

https://repl.it/repls/CumbersomeImmediateLibrary

aakarsh
  • 21
  • 4