new Date().toLocaleDateString() will return today’s date in your local format.
Some dates will be strings, others timestamps, and others date formats you might not be familiar with.
There are several ways to manipulate and format dates in JS:
- Use Node.js libraries like moment.js or dateformat
- Code your own functions to display dates
Date object constructor takes many elements as parameters.
new Date() // creates a Date object with the time at instantiation new Date(timestamp) // takes a "timestamp" number new Date(string) // takes a string parseable as Date.parse() new Date(year, monthIndex) // monthIndex starts at 0, March is 2, May is 4 new Date(year, monthIndex, day) new Date(year, monthIndex, day, hour) new Date(year, monthIndex, day, hour, minute) new Date(year, monthIndex, day, hour, minute, seconds) new Date(year, monthIndex, day, hour, minute, seconds, milliseconds)
toDateString() method returns a string containing, in English:
- The day in 3 letters
- The month in 3 letters
- The day of the month in 2 digits
- The year in 4 digits
For example, with today’s date:
const myDate = new Date() myDate.toDateString() // 'Wed Oct 20 2021'
toUTCString() method returns a string similar to
toDateString() but with the time and the time zone:
const myDate = new Date() myDate.toUTCString() // 'Wed, 20 Oct 2021 12:50:02 GMT'
Date object from a timestamp.
const timestamp = new Date(1634726212 * 1000)
Date object constructor also takes a string as a parameter.
new Date(string) // takes a string parseable as Date.parse()
💡 However, this way of instantiating a date is strongly discouraged because the result depends on
A better solution is to use
moment.js, which has a much more reliable date instantiation method.
Like other node packages, you can install moment.js with npm, yarn, or another node package manager.
npm install moment --save # with npm yarn add moment # with Yarn
Another solution is to use the moment.js library. Using the
unix function takes your UNIX timestamp in the correct format without requiring you to multiply it by 1000.
import moment from "moment" const timestamp = moment.unix(1634726212)
To display it in the format you desire, simply apply the
format method to your timestamp object.
timestamp.format("dd/mm/yy") // 11:36:52
To install it with npm:
npm install dateformat
import dateFormat from "dateformat" const now = new Date() dateFormat(now, "dd/mm/yyyy")
And there you have it! You now know how to change date formats in JS, regardless of their initial form.
Hey, I'm Thomas 👋 Here, you'll find articles about tech, and what I think about the world. I've been coding for 20+ years, built many projects including Startups. Check my About/Start here page to know more :).