Web development and Tech news Blog site. WEBISFREE.com

HOME > js

JavaScript date and time library - momentjs information and examples

Last Modified : 06 Mar, 2023 / Created : 06 Mar, 2023
View Count
Learn about the well-known momentjs library for date in JavaScript.

! What is moment.js?

It is one of the most widely used libraries when it comes to obtaining or changing date and time-related values using JavaScript. For instance, it enables you to easily obtain complex dates and times like yesterday’s date or one week ago, one month ago and so on. Furthermore, it allows you to change the date format and select the desired date conveniently, and its advantages also include providing various languages.

  • Easily obtain desired formats for date and time.
  • Can easily retrieve specific date values such as yesterday or one year ago.
  • Various language settings are available.

Then let's first check the installation method.

# Installation momentjs

This is the way to install momentjs first. You can install it using npm as shown below.
npm i moment

Now the installation process using npm is complete. You can import and use it as follows:
import moment from 'moment';

Now, let's explore various ways and examples of how to use the installed moment one by one.

! Getting timestamps using moment.js

You can obtain the timestamp value for the desired date and time. You use two functions as follows.
unix() // unix timestamp value(second)
valueOf() // full timestamp

Both are available for use, and unix() returns a value in seconds while valueOf() returns a value in milliseconds. Let's create a simple example to obtain a timestamp value.

// Result

As shown above, I was able to obtain the timestamp value.

! moment.js Get the value at 0 o'clock and 0 minutes today.

This is a way to calculate the time from 0:00 today. In this case, if you input today's date but not the time, you can get the value based on 0:00.

@ Today, September 1st, 2020 at 0:00:00 (midnight)
moment({ year :2020, month :9, day :1}).valueOf();

! Calculating the previous time, subtract()

Using subtract() in moment, you can get the desired date before this day.

moment(Date).subtract(Previous date, Date-based)

날짜 기준의 값으로 년, 월, 일 또는 주(week) 및 시, 분 등도 가능합니다.

- y // previous year
- M // previous month
- d // previous date
- h // previous hour
- m // previous minute

The following is a simple example.

@ 7 days ago, getting a week's worth of time.

@ Obtaining time one month ago, three months ago.

So far, we have learned about the ways to use momentjs here.


JavaScript history object allows page transition without page refreshing and pushstate


Ways to initialize JavaScript array all values to 0