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);
Javascript: Convert timestamp to human readable date?
You can use the Number
data type instead of date * 1000
to achieve this. See code example below:
// generate a timestamp
var timestamp = Number(new Date()) //1479895361931
Then
// get the date representation from the timestamp
var date = new Date(timestamp) // Wed Nov 23 2016 18:03:25 GMT+0800 (WITA)
Convert timestamp to a specific date format in javascript
How you can convert /Date(1231110000000)/
to DD/MM/YYYY
format :
function convert(timestamp) { var date = new Date( // Convert to date parseInt( // Convert to integer timestamp.split("(")[1] // Take only the part right of the "(" ) ); return [ ("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes ("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes date.getFullYear() // Get full year ].join('/'); // Glue the pieces together}
console.log(convert("/Date(1231110000000)/"));
Timestamp to human readable format
getDay()
returns the day of the week. To get the date, use date.getDate()
. getMonth()
retrieves the month, but month is zero based, so using getMonth() + 1
should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC
to the methods (e.g. date.getUTCFullYear()
, date.getUTCHours()
)
const timestamp = 1301090400;
const date = new Date(timestamp * 1000);
const datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
Here is a small helper idea to retrieve values of a given Date
:
const dateHelper = dateHelperFactory();
const formatMe = date => {
const vals = `yyyy,mm,dd,hh,mmi,ss,mms`.split(`,`);
const myDate = dateHelper(date).toArr(...vals);
return `${myDate.slice(0, 3).join(`/`)} ${
myDate.slice(3, 6).join(`:`)}.${
myDate.slice(-1)[0]}`;
};
// to a formatted date with zero padded values
console.log(formatMe(new Date(1301090400 * 1000)));
// the raw values
console.log(dateHelper(new Date(1301090400 * 1000)).values);
function dateHelperFactory() {
const padZero = (val, len = 2) => `${val}`.padStart(len, `0`);
const setValues = date => {
let vals = {
yyyy: date.getFullYear(),
m: date.getMonth()+1,
d: date.getDate(),
h: date.getHours(),
mi: date.getMinutes(),
s: date.getSeconds(),
ms: date.getMilliseconds(), };
Object.keys(vals).filter(k => k !== `yyyy`).forEach(k =>
vals[k[0]+k] = padZero(vals[k], k === `ms` && 3 || 2) );
return vals;
};
return date => ( {
values: setValues(date),
toArr(...items) { return items.map(i => this.values[i]); },
} );
}
.as-console-wrapper {
max-height: 100% !important;
}
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");
How do I convert a Firestore date/Timestamp to a JS Date()?
The constructor for a JavaScript's Date
doesn't know anything about Firestore's Timestamp
objects — it doesn't know what to do with them.
If you want to convert a Timestamp
to a Date
, use the toDate()
method on the Timestamp
.
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
Related Topics
How to Replace Captured Groups Only
Es6 Promise.All() Error Handle - Is .Settle() Needed
How to Get a JavaScript Object Property Name That Starts with a Number
Add Event Handler to HTML Element Using JavaScript
JavaScript Getelementbyid() Not Working
JavaScript Detect an Ajax Event
Create <Div> and Append <Div> Dynamically
Differencebetween Parseint(String) and Number(String) in JavaScript
What Are the Current Cookie Limits in Modern Browsers
Is Onload Equal to Readystate==4 in Xmlhttprequest
Iterate Over Object Literal Values
Displaying a Number in Indian Format Using JavaScript
JavaScript Inheritance: Object.Create VS New
Getting Key with the Highest Value from Object
How to Calculate the Latlng of a Point a Certain Distance Away from Another
What Does ${} (Dollar Sign and Curly Braces) Mean in a String in JavaScript
JavaScript Es6 Class Definition Not Accessible in Window Global