Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

The moment.js package is a node module that allows us to manipulate dates and times according to our preferences. The fromNow() method, for instance, will enable us to get the difference in time between one time and the present time.

Syntax

time.fromNow([true])
Syntax for fromNow() method in Momen.js

Parameters

time: This is the time we want to check, to see how far it is from the current time.

true: This is used to remove the suffix "ago".

Return value

The value returned is a string denoting the time that has passed between the time specified and now.

Example

Let's view a code 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])
// get time from now
console.log(time1.fromNow()) // 12 years ago
console.log(time2.fromNow()) // a few seconds ago
console.log(time3.fromNow(true)) // 11 years (no "ago" suffix)
console.log(time4.fromNow()) // in x hours
console.log(time5.fromNow()) // in y month
console.log(time6.fromNow()) // in 3 years
Get the difference between present time and any time in moment.js

Explanation

  • Line 2: We require the moment.js package.
  • Lines 5–10: We create some dates and times.
  • Lines 13–18: We use the fromNow() method of moment.js to get the difference in time between the dates and time we created and the present time.

RELATED TAGS

javascript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring