Convert a UNIX Timestamp to a YYYY-MM-DD Format
How can you convert a UNIX timestamp into a date with the YYYY-MM-DD
format?
Below are four different methods, one in pure JavaScript and three others using NPM packages.
Let's get started!
Method 1 - Pure JavaScript
First, let's go over a pure JavaScript solution that doesn't require you to import any external NPM package or library:
// convert timestamp to date object
// convert the timestamp to milliseconds by multiplying it by 1,000
const date = new Date(timestamp * 1000);
// get the current year in YYYY digit format
const year = date.getFullYear();
// get the month in a 2-digit format
// getMonth() returns an index position of the month in an array.
// Therefore, we need to add 1 to get the correct month.
// toLocaleString() converts any single digit months to have a leading zero (i.e. "2" => "02")
let month = date.getMonth() + 1;
month = month.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });
// get the current day of the month
// toLocaleString() converts any single digit days to have a leading zero (i.e. "8" => "08")
let day = date.getDate();
day = day.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });
// combine the year, month, and day into one string to create the "YYYY-MM-DD" format
const dateString = `${year}-${month}-${day}`;
// example output: "2023-04-02"
Make sure you replace timestamp
with your UNIX timestamp.
Method 2 - Day.js
If you're fine with using an external library, the Day.js NPM package makes this pretty easy:
import dayjs from "dayjs";
const date = dayjs.unix(timestamp).format("YYYY-MM-DD");
// example output: "2023-04-02"
Make sure you replace timestamp
with your UNIX timestamp.
Day.js does all the hard work for us! And the size of the package is only 2kb.
Method 3 - Moment.js
Another great NPM package is Moment.js.
It also makes formatting dates quite simple:
import moment from "moment";
moment.unix(timestamp).format("YYYY-MM-DD");
// example output: "2023-04-02"
Make sure you replace timestamp
with your UNIX timestamp.
Method 4 - Luxon
Luxon is another good NPM package you could use for this:
import { DateTime } from "luxon";
const date = DateTime.fromSeconds(timestamp);
const formattedDate = date.toFormat("yyyy-LL-dd");
// example output: "2023-04-02"
Make sure you replace timestamp
with your UNIX timestamp.
Thanks for reading and happy coding!