What is the moment.toString() method in moment.js?

Overview

We can use the toString() method of the time manipulation and display library moment.js to return an English representation of a time or date.

Syntax

time.toString()

Parameters

time: This is the time or date we want to get in English representation.

Return value

A string is returned in English, which represents the date or time specified.

Example

// require the moment module
const moment = require("moment")
// create some dates and time
const time1 = moment([2010, 1, 14, 10, 25, 50, 125])
const time2 = moment(new Date) // current date and time
const time3 = moment(1318781876406)
const time4 = moment({hour: 20, minute: 20, second: 34})
const time5 = moment([2022, 5, 17])
const time6 = moment([2025, 4, 18])
const time7 = moment().add(25, "seconds");
// get ISO8601 of time
console.log(time1.toString())
console.log(time2.toString())
console.log(time3.toString())
console.log(time4.toString())
console.log(time5.toString())
console.log(time6.toString())
console.log(time7.toString())

Explanation

  • Line 2: We require the moment.js package.
  • Lines 5–11: We create some dates and times.
  • Lines 14–20: With the toString() method, we get the string representation of the times and dates. Then, with the console.log() function, we print these strings to the console.

Free Resources