Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- use the F12 key in Chrome and other chromium-based browsers.
- use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).
The new Date() function without any parenthesis creates an object with the current date. We can also pass arguments to the new Date() function to create new date objects with specified date and time. Please see this article to know more about the Date Object and methods which we can use to operate on the date object.
How to format the Date Object
We will start with the toDateString() method; The toDateString() method can be used to get the date in the following format:
[ Day Month Date Year ]
This method is used to get only the date part from the whole date string.
The toTimeString() method is used to get the time from the date string. It outputs the time in the following format:
[ Hours:Minutes:Seconds Time Zone (Time Zone Name) ]
This method is used to get the date in ISO format. This format gives the date in the zero UTC time zone.
This method formats the date in a localized string format. This function takes a language and a country in standard locale code format, i.e., ‘en-US’ as a parameter, and formats the date according to the desired (specified) locale.
The “get” methods
We can use the getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() and getMilliseconds() methods to output the date in our required format.
The getFullYear() method can be used to get only the value of the year stored in the date object. Similarly, getMonth(), getDate(), getHours(), getMinutes(), getSeconds() and getMilliseconds() can be used to get the individual values of Month, Date, Hours, Minutes, Seconds and Milliseconds respectively.
We can combine any of these methods to get a date in our required format. In this example, we will format the date in the following way:
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
console.log(d + "/" + m + "/" + y)