To convert a Unix timestamp to the format yyyy-mm-dd
using JavaScript, you can use the Date
object along with some additional methods to extract the year, month, and day. Here's an example function that performs the conversion:
function convertUnixTimestamp(timestamp) {
const date = new Date(timestamp * 1000); // Convert timestamp to milliseconds
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Month is zero-based
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
In this function, we create a new Date
object by multiplying the Unix timestamp by 1000 to convert it from seconds to milliseconds. Then, we use the getFullYear()
, getMonth()
, and getDate()
methods of the Date
object to extract the year, month, and day components.
Since the getMonth()
method returns a zero-based index (0 for January, 1 for February, etc.), we add 1 to the result and use String()
and padStart()
methods to ensure that the month and day are always two digits.
Finally, we return the formatted string in the yyyy-mm-dd
format.
Here's an example usage of the function:
const unixTimestamp = 1621848620; // Replace with your Unix timestamp
const formattedDate = convertUnixTimestamp(unixTimestamp);
console.log(formattedDate); // Output: 2021-05-24
Make sure to replace 1621848620
with your actual Unix timestamp in seconds. The formattedDate
variable will contain the converted date in the yyyy-mm-dd
format.
Comments
Post a Comment