What is the moment().valueOf() method in Moment.js?

Overview

The moment.js library is a time manipulation library that provides us with the valueOf() method. This method returns the number of seconds since the Unix Epoch, such as January 1st, 1970 at 00:00:00 UTC. It converts the time passed to it into a Unix time.

Syntax

We have the syntax for the valueOf() method in the following code widget:

time.valueOf()
syntax for valueOf() method in moment.js

Parameters

time: This is the date or time for which we want to return the number of seconds in milliseconds since the Unix epoch.

Return value

An integer, which is in milliseconds, represents a Unix time that is returned.

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 the difference between one time and another
console.log(time1.valueOf())
console.log(time2.valueOf())
console.log(time3.valueOf())
console.log(time4.valueOf())
console.log(time5.valueOf())
console.log(time7.valueOf())

Explanation

  • Line 2: We require the moment package.
  • Lines 5–11: We create some dates and times.
  • Lines 14–19: We use the valueOf() method to get their number of milliseconds since the Unix epoch.

Free Resources