Open In App

Moment.js Twitter Plugin

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

To format dates like Twitter, nodes have an external npm module, moment.twitter.js which is an extension of moment.js. 

This package can be installed by using the following command:

npm install moment-twitter

 

moment.twitter.js has two different methods as listed below:

1. twitterLong() Method: It is used for long date formatting like in Web-based Twitter (n hours)

Syntax:

moment().twitterLong()

Parameters: This method does not accept any parameters.

Return Value: This method returns web-based Twitter dates.

The below examples will demonstrate moment.twitterLong() method.

Example 1:

Javascript




const moment = require('moment-twitter');
 
// Formats time relative to current time
// Adding 10 hours
hours = moment(moment() + (36e5 * 10))
console.log(hours.twitterLong())
 
// Adding 1 hour
hours = moment(moment() + (36e5 * 1))
console.log(hours.twitterLong())


Output:

10 hrs
1 hr

Example 2:

Javascript




const moment = require('moment-twitter');
 
// When time is greater than 24 hours,
// output will be in dates
hours = moment(moment() + (6048e5 * 1))
console.log(hours.twitterLong())


Output:

Aug 8

2. moment().twitter() Method: It is used for mobile like Twitter dates (nh). It is an alias for moment().twitterShort().

Syntax:

moment().twitterLong()

Parameters: This method does not accept any parameters.

Return Value: This method returns mobile-based Twitter dates.

The below examples will demonstrate the moment.twitter() method.

Example 1:

Javascript




const moment = require('moment-twitter');
 
// Output will be in units and
// single character.
hours = moment(moment() + (36e5 * 7))
console.log(hours.twitter())


Output:

7h

Example 2:

Javascript




const moment = require('moment-twitter');
 
// When time is greater than 24 hours
hours = moment(moment() + (256e5 * 7))
console.log(hours.twitter())


Output:

2d

Reference: https://momentjs.com/docs/#/plugins/twitter/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads