I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?
For example, in HH/MM/
In the new world, we should be moving towards the standard Intl JavaScript object, that has a handy DateTimeFormat constructor with .format() method:
function format_time(s) {
const dtFormat = new Intl.DateTimeFormat('en-GB', {
timeStyle: 'medium',
timeZone: 'UTC'
});
return dtFormat.format(new Date(s * 1e3));
}
console.log( format_time(12345) ); // "03:25:45"
But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss
:
function format_time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
console.log( format_time(12345) ); // "03:25:45"
Method Date.prototype.toISOString() returns time in simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e.
YYYY-MM-DDTHH:mm:ss.sssZ
or±YYYYYY-MM-DDTHH:mm:ss.sssZ
respectively). The timezone is always zero UTC offset.
This solution does not require any third-party libraries and is supported in all browsers and JavaScript engines.