Convert Unix Timestamp to Date Time (Javascript)

Convert a Unix timestamp to time in JavaScript

let unix_timestamp = 1549312452// Create a new JavaScript Date object based on the timestamp// multiplied by 1000 so that the argument is in milliseconds, not seconds.var date = new Date(unix_timestamp * 1000);// Hours part from the timestampvar hours = date.getHours();// Minutes part from the timestampvar minutes = "0" + date.getMinutes();// Seconds part from the timestampvar seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 formatvar formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);

Convert UNIX timestamp to date time (javascript)

You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :

var d = new Date(timestamp*1000);

Reference

How to convert unix timestamp to calendar date moment.js

Using moment.js as you asked, there is a unix method that accepts unix timestamps in seconds:

var dateString = moment.unix(value).format("MM/DD/YYYY");

Convert unix timestamp to javascript date Object

Duplicate of How to format a JSON date?.

Accepted solution was:

var date = new Date(parseInt(jsonDate.substr(6)));

How to convert a Unix timestamp to 2000-01-01 or 2000-05-24 20:00:00 format or reverse in Deno?

Aside from the standard Javascript ways, there is a date/time library for Deno called Ptera, that can be used as follows:

import { datetime } from "https://deno.land/x/ptera/mod.ts";

const dt = datetime("2000-05-24 20:00:00");
console.log(dt.format("X")); // X for Unix timestamp in seconds 959198400
console.log(dt.format("x")); // x for "Unix timestamp" in milliseconds 959198400000

const dt2 = datetime(1646245390158);
console.log(dt2.format("YYYY-MM-dd HH:mm:ss")); // output: 2022-03-02 19:23:10

A UNIX timestamp is the number of seconds since 1970-01-01 00:00:00 UTC, the Javascript timestamp is in milliseconds and sometimes in documentations, they also call this as a UNIX timestamp or UNIX Epoch time.

A detailed reference about the formatting options is available here.

from unix timestamp to datetime

Note my use of t.format comes from using Moment.js, it is not part of JavaScript's standard Date prototype.

A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.

The presence of the +0200 means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.

If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:

var t = new Date( 1370001284000 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");

If your timestamp string is in seconds, then use setSeconds:

var t = new Date();
t.setSeconds( 1370001284 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");


Related Topics



Leave a reply



Submit