How to use Date object with toString() Method In Javascript
We can convert the current date to a string using the toString() method and then split it into an array of words using the space delimiter. Thereafter, the splice method is used on the array to keep the words from indices 1 to 3 i.e. the day, month and the year. Finally, the join method is used to join the resultant array.
Example: The below code uses the Date object with toString() method and its associated methods to log the current date in JavaScript.
Javascript
// Create a new Date object const currentDate = new Date(); console.log( "Before Split: " , currentDate.toString()); console.log( "After Split: " , currentDate.toString(). split( ' ' ).splice(1, 3).join( ' ' )); |
Before Split: Tue Jan 23 2024 09:17:49 GMT+0000 (Coordinated Universal Time) After Split: Jan 23 2024
How to Log the Current Date in JavaScript ?
The Date object is an inbuilt object constructor of JavaScript language. It is used to work with dates and times. The Date object is created by using the new keyword, i.e. new Date(). The current date can be logged on the console in JavaScript using the below-discussed methods.
Table of Content
- Using JavaScript Date object
- Using JavaScript Date object with toString() Method
- Using JavaScript Date object with toDateString() Method
- Using JavaScript Date object with toLocaleDateString() Method
- Using JavaScript Date object with toISOString() Method
Contact Us