Moment JS with Example Using Node.js
source link: https://www.js-tutorials.com/nodejs-tutorial/moment-js-with-example-using-node-js/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
in this post, we’ll learn about the moment js library for validating, parsing and manipulating dates with times.
It’s always been a challenge to work with dates and timings. The JavaScript library for handling dates has always seemed useful to me.
what is moment js
The Moment.js is a fantastic JavaScript package that allows you to manipulate dates in the browser, You can use this lib with angular, react, node.js etc. In Moment.js, the moment object is mutable. It indicates that operations such as add, subtract, and set modify the original moment object.
Shorthand Keys
Key Shorthand
years y
quarters Q
months M
weeks w
days d
hours h
minutes m
seconds s
milliseconds ms
How To Use Moment JS with Node.js
Let’s create a nodejs app to implement the moment.js
library.
Create Project and Install Dependencies
We’ll create a project using following command:
mkdir test-moment
cd test-moment
Now, Install moment.js using the following command:
npm install moment --save
Create a file called server.js
in the root directory and add the following code to it.
Let’s start the node.js server
node server.js
The moment()
returns the current date and time, whereas format() converts the current date and time to the format supplied.
Output :14/12/2021
How To Add Date Using moment.js
Let’s add some days, months, and years into a given date.
Syntax :
Examples:
Output :
Method chaining with Nodejs
Output :
How To Subtract Date Using moment.js
Let’s add some days, months, and years into a given date.
Syntax :
Examples:
Output :
Difference Between Dates Using moment.js
The diff()
method in the js library is used to compare two dates. It takes a date as its first argument. A second input can be used to specify the time unit.
Output :
Moment.js Date Comparison Methods
The moment.js library have isBefore()
, isAfter()
, and isSame()
methods for comparing dates. These methods return Boolean values that are indicating if one date is before, after, or equal to another date.
Output :
You can find more about on the moment official documentation.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK