/

A Moment.js tutorial: Managing Dates in JavaScript

A Moment.js tutorial: Managing Dates in JavaScript

Moment.js is a powerful JavaScript library that provides convenient ways to handle dates in both the browser and Node.js environments. In this tutorial, we will explore the basics and most common usages of Moment.js.

Installation

To include Moment.js in your project, you can either directly include it using a script tag from unpkg.com like this:

1
<script src="https://unpkg.com/moment"></script>

Alternatively, you can install it using npm like this:

1
npm install moment

If you choose to install Moment.js using npm, you need to import it using either ES Modules syntax:

1
import moment from 'moment'

…or CommonJS syntax:

1
const moment = require('moment')

Get the current date and time

To get the current date and time, simply call the moment() function:

1
const date = moment()

Parse a date

You can initialize a Moment.js object with a specific date by passing it a string:

1
const date = moment(string)

Moment.js accepts various date formats, including ISO 8601, RFC 2822 Date Time, and formats accepted by the built-in Date object.

ISO 8601 is the most commonly used format. Here are some format reference examples:

Format Meaning Example
YYYY 4-digit year 2018
YY 2-digit year 18
M 2-digit month (without leading zero) 7
MM 2-digit month 07
MMM 3-letter month abbreviation Jul
MMMM Full month name July
dddd Full day name Sunday
gggg 4-digit week year 2018
gg 2-digit week year 18
w Week of the year (without leading zero) 18
ww Week of the year 18
e Day of the week (starts at 0 for Sunday) 4
D 2-digit day (without leading zero) 9
DD 2-digit day 09
Do Day number with ordinal (e.g., 9th) 9th
T Indicates the start of the time part -
HH 2-digit hours (24-hour format) from 0 to 23 22
H 2-digit hours (24-hour format) from 0 to 23 (without leading zero) 22
kk 2-digit hours (24-hour format) from 1 to 24 23
k 2-digit hours (24-hour format) from 1 to 24 (without leading zero) 23
a/A am or pm pm
hh 2-digit hours (12-hour format) 11
mm 2-digit minutes 22
ss 2-digit seconds 40
s 2-digit seconds (without leading zero) 40
S 1-digit milliseconds 1
SS 2-digit milliseconds 12
SSS 3-digit milliseconds 123
Z Timezone offset +02:00
x UNIX timestamp in milliseconds 1410432140575

Set a date

You can set a specific date using the set() method:

1
moment().set({ year: 2018, month: 6, date: 15 })

Format a date

To format a date according to your needs, use the format() method:

1
date.format(string)

The string format accepts the same symbols and formats mentioned earlier in the “Parse a date” section.

Here’s an example of formatting a date:

1
moment().format("YYYY Do MM")

Moment.js also provides constants that you can use instead of custom formats. For example:

Constant Format Example
moment.HTML5_FMT.DATETIME_LOCAL YYYY-MM-DDTHH:mm 2017-12-14T16:34
moment.HTML5_FMT.DATETIME_LOCAL_SECONDS YYYY-MM-DDTHH:mm:ss 2017-12-14T16:34:10
moment.HTML5_FMT.DATETIME_LOCAL_MS YYYY-MM-DDTHH:mm:ss.SSS 2017-12-14T16:34:10.234
moment.HTML5_FMT.DATE YYYY-MM-DD 2017-12-14
moment.HTML5_FMT.TIME HH:mm 16:34
moment.HTML5_FMT.TIME_SECONDS HH:mm:ss 16:34:10
moment.HTML5_FMT.TIME_MS HH:mm:ss.SSS 16:34:10.234
moment.HTML5_FMT.WEEK YYYY-[W]WW 2017-W50
moment.HTML5_FMT.MONTH YYYY-MM 2017-12

Validating a date

You can check if a date is valid using the isValid() method:

1
2
moment('2018-13-23').isValid() // false
moment('2018-11-23').isValid() // true

Time ago, time until date

To get a human-readable representation of a date relative to the current date, you can use the fromNow() method. The strings returned are localized automatically:

1
2
3
moment('2016-11-23').fromNow() // 2 years ago
moment('2018-05-23').fromNow() // a month ago
moment('2018-11-23').fromNow() // in 5 months

If you only want to show the time difference without referring to past or future, you can pass true to the fromNow() method:

1
2
3
moment('2016-11-23').fromNow(true) // 2 years
moment('2018-05-23').fromNow(true) // a month
moment('2018-11-23').fromNow(true) // 5 months

Manipulate a date

You can add or subtract any amount of time to a date using the add() and subtract() methods:

1
2
moment('2016-11-23').add(1, 'years')
moment('2016-11-23').subtract(1, 'years')

The available units of time are:

  • years
  • quarters
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds
  • milliseconds

Tags: JavaScript, Moment.js, Date management, Time manipulation, Formatting dates