- Using the toString()
- Using the toISOString()
- Using the Moment.js format()
Method 1: Using the toString() Method
By default, there is no necessary parameter that needs to be passed.
- If no parameter is passed, it will return the current date and time as a string.
It is a Date and time in the form of a string.
let dateObj = new Date(); let text = dateObj.toString(); console.log(text);
Sat Mar 19 2022 12:19:24 GMT+0530 (India Standard Time)
const date = new Date(2022, 2); let text = date.toString(); console.log(text);
Tue Mar 01 2022 00:00:00 GMT+0530 (India Standard Time)
Method 2: Using the toISOString() method
The toISOString() is a built-in Date class method that converts the date object into the ISO string format.
const date = new Date(); console.log(date.toISOString());
Method 3: Using the Moment.js format() Method
The Moment.js format() method is used to convert a date to a string in various formats. First, you need to include the library in your project. Once it’s included, you can use it as follows:
date = moment().format('YY – MM - DD HH : mm : ss');
All parameters of the moment.format() method is optional.
- YY: It represents the year.
- MM: It represents the Month.
- DD: This parameter is for the day.
- HH: It is for hours.
- mm: It is for the minutes.
- ss: It represents the seconds.
const moment = require('moment'); const date = moment(); console.log(date.format()); console.log(date.format('MMMM Do YYYY, h:mm:ss a'));
2023-08-18T05:58:28+05:30 August 18th 2023, 5:58:28 am