How to Convert Date to String in JavaScript

Here are three ways to convert a date to a string in JavaScript:

  1. Using the toString()
  2. Using the toISOString()
  3. Using the Moment.js format()

Method 1: Using the toString() Method

JavaScript Date toString() method does not accept any arguments. When called, it simply converts the date and time information of the Date object on which it is called to a human-readable string in the default format specific to implementing the JavaScript engine and the local timezone of the client’s system.

Syntax

Date.toString()

Parameters

By default, there is no necessary parameter that needs to be passed.

  1. If no parameter is passed, it will return the current date and time as a string.
  2. If the parameter is passed in any format other than string data types, the JavaScript will return the date in string format for that date entered by the user.

Return value

It is a Date and time in the form of a string.

Example 1

let dateObj = new Date();

let text = dateObj.toString();

console.log(text);

Output

Sat Mar 19 2022 12:19:24 GMT+0530 (India Standard Time)

Example 2

const date = new Date(2022, 2);

let text = date.toString();

console.log(text);

Output

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.

Syntax

date.toISOString()

Example

const date = new Date();

console.log(date.toISOString());

Output

2023-08-18T00:23:20.580Z

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:

Syntax

date = moment().format('YY – MM - DD HH : mm : ss');

Parameters

All parameters of the moment.format() method is optional.

  1. YY: It represents the year.
  2. MM: It represents the Month.
  3. DD: This parameter is for the day.
  4. HH: It is for hours.
  5. mm: It is for the minutes.
  6. ss: It represents the seconds.

Example

const moment = require('moment');

const date = moment();

console.log(date.format());

console.log(date.format('MMMM Do YYYY, h:mm:ss a'));

Output

2023-08-18T05:58:28+05:30
August 18th 2023, 5:58:28 am

That’s it!

Related posts

How to Convert String to Date

How to Convert Timestamp to Date

How to Convert Date to Timestamp