JavaScript: Convert a Unix timestamp to time
JavaScript Datetime: Exercise-17 with Solution
Unix to Time
Write a JavaScript function to convert a Unix timestamp to time.
Test Data:
console.log(Unix_timestamp(1412743274));
10:11:14
Sample Solution:
JavaScript Code:
Output:
10:11:14
Explanation:
In the exercise above,
- The code defines a JavaScript function named "Unix_timestamp()" with one parameter 't', which represents a UNIX timestamp (number of seconds since January 1, 1970).
- Inside the function:
- It creates a new Date object named 'dt' by converting the UNIX timestamp to milliseconds (by multiplying it by 1000).
- It extracts the hours component from the 'dt' Date object and stores it in the variable 'hr'.
- It extracts the minutes component from the 'dt' Date object, pads it with a leading zero if necessary (using the "substr()" method), and stores it in the variable 'm'.
- It extracts the seconds component from the 'dt' Date object, pads it with a leading zero if necessary (using the "substr()" method), and stores it in the variable 's'.
- It constructs a string representation of the time in the format 'hours:minutes:seconds' and returns it.
- The code then demonstrates the usage of the "Unix_timestamp()" function by calling it with the UNIX timestamp 1412743274.
Flowchart:
Live Demo:
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to count the number of days passed since beginning of the year.
Next: Write a JavaScript program to calculate age.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics