Firstly let's create a new date object, it will be the current date and time according to your machine.
let date = new Date();
Date to String and Format
Thu Aug 27 2020 05:17:24 GMT+0100 (British Summer Time)
Thu Aug 27 2020
05:19:09 GMT+0100 (British Summer Time)
Thu, 27 Aug 2020 04:20:08 GMT
let date = new Date(); let formatted = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear(); console.log(formatted);
YYYY-MM-DD HH:MM:SS Format
Here is another example, this time with hours minutes and seconds included.
let date = new Date(); let formatted = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() console.log(formatted);
Numerical Month to Words
There is no way to natively provide months in a written format in a custom date format. We can make a function that does this by creating an array of months then using the
getMonth method to select a month by its index.
let date = new Date(); let m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']; let formatted = date.getDate() + "-" + m[date.getMonth()] + "-" + date.getFullYear(); console.log(formatted);
Date object. They are useful for obtaining single numerical elements from a date such as the day of the week and the date of the month.
getDay is a numerical representation of the day of the week - Monday
note - months start from
0, like an array index.
getSeconds starts at
0 and ends at
get methods to convert a local timezone into UTC. It works by adapting the time on your device based on its timezone.