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/SS
format.
UNIX timestamps can be converted to time using 2 approaches: Method 1: Using the toUTCString() method: As JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object.
The UNIX timestamp is an integer value that represents the number of seconds elapsed since UNIX Epoch on January 1st, 1970 at 00:00:00 UTC. In short, it is a way to track the time as a running total of seconds. Hence, a UNIX timestamp is simply the number of seconds between a specific date and the UNIX Epoch.
Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.
function timeConverter(UNIX_timestamp){ var a = new Date(UNIX_timestamp * 1000); var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; var year = a.getFullYear(); var month = months[a.getMonth()]; var date = a.getDate(); var hour = a.getHours(); var min = a.getMinutes(); var sec = a.getSeconds(); var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ; return time; } console.log(timeConverter(0));
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 timestamp var hours = date.getHours(); // Minutes part from the timestamp var minutes = "0" + date.getMinutes(); // Seconds part from the timestamp var seconds = "0" + date.getSeconds(); // Will display time in 10:30:23 format var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2); console.log(formattedTime);
For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With