Managing Dates and Times Using Moment.js
What Is Moment.js?
In this article I’ll show you how to get up and running with Moment.js, as well as demonstrate several of its common use cases.
Warning for New Users: Use date-fns Instead
Note that as of September 2020, we are recommending that users looking to implement a date library use date-fns instead .
Moment.js is a fairly heavy library for its function, and the Chrome dev tools now actively recommend against using it as part of Core Web Vitals performance testing. As a result, the project is in maintenance mode and new feature development is no longer on the table according to the Moment.js maintainers.
Getting Started with Moment.js
Moment.js is freely available for download from the project’s home page . Moment.js can be run from the browser as well as from within a Node application. In order to use it with Node, install the module using the following command.
Then, simply require() and use it in your application as shown below.
In order to run Moment.js from the browser, include it using a <script> tag, as shown below. Moment.js creates a global moment object which can be used to access all the date and time parsing and manipulation functionality.
In the past, I recall converting date strings into Date objects, grabbing individual pieces of data, and then performing string concatenations. Moment.js has simplified the process of date conversion to any particular format. Date format conversion with Moment is simple, as shown in the following example.
Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.
See the Pen Formatting the Date with Moment.js by SitePoint ( @SitePoint ) on CodePen .
Tip : Try experiment with some of the other date formats listed in the project’s documentation .
Another annoying task that Moment.js has greatly simplified is date validation. In order to perform validation, simply pass a date string to the moment object, along with the desired date format, and call the isValid() method. This will return true if the date is valid, and false otherwise.
Be aware, however, that Moment gives you the possibility to work with partial dates, which might lead to unexpected results.
To avoid this, you can put Moment into strict parsing mode by passing it true as a third argument.
Here’s an example to showcase this functionality.
See the Pen Checking Date Validity with Moment.js by SitePoint ( @SitePoint ) on CodePen .
There are a number of other helpful flags in the object returned by moment() :
- overflow – This is set when an overflow occurs. An example would be the 13th month or 32nd day.
- invalidMonth – Set when the month is invalid, like Jannnuaarry.
- empty – Set when the entered date contains nothing parsable.
- nullInput – Set when the entered date is null .
You can read more about these and other available flags on the project’s homepage .
There are a number of options for manipulating the moment object. For example, you can add or subtract days, months, years, etc. This is achieved via the add() and subtract() methods. The following example shows how seven days, months, or weeks are added to the current date.
Similarly, the subtract() method is shown below.
Note that each of the above examples will return the moment object. If you want a human-readable date, you’ll need to format it accordingly.
Time From Now
Another common task is determining how much time exists between two dates. For calculating time from the current date, Moment.js uses a method named fromNow() . Here’s how to check how much time has elapsed since the beginning of the decade:
If we pass in true as an argument, we can get the value without the suffix.
Time From Another Date
The fromNow() method is used to compare time to the current date. This is just a special case of from() , which compares two arbitrary dates. An example that utilizes from() is shown below.
You can have a play with this method in the following demo.
See the Pen Time From Another Date with Moment.js by SitePoint ( @SitePoint ) on CodePen .
Calculating the Difference Between Dates
Moment.js offers a way to calculate the difference between two dates. The difference is calculated in milliseconds by default, but can also be returned in days, months, years, etc. To compute the difference, call the diff() method. This method takes a date as its first argument. The unit of time can be specified using the optional second argument. If this is not included, then milliseconds are used. The following example and demo illustrate how diff() is used.
See the Pen Calculating the Difference Between Dates with Moment.js by SitePoint ( @SitePoint ) on CodePen .
Moment.js also provides various date comparison methods . These methods include isBefore() , isAfter() , and isSame() which, as the names imply, return a Boolean indicating if one date is before, after, or equal to another date. An example that uses isAfter() is shown below.
There is also an isLeapYear() method that checks for leap years.
International Language Support
Moment.js offers great i18n support . It allows you to assign a global language or set the language for a particular moment object. By default, it supports the English language. If you want to support any other language, then assign the key values of that particular language to moment.locale . The following abridged example, taken from the Moment.js docs , shows how support can be added for French.
See the Pen Internationalization with Moment.js by SitePoint ( @SitePoint ) on CodePen .
Why Moment Might Not Be a Good Fit
Although Moment.js is an excellent time and date library, it is also something of a behemoth. For example, if you use it with webpack, just an innocent require('moment'); is enough ensure that all of the locales come along for the ride. This significantly increases your bundle size and you need to resort to plugins to get it back down.
It also comes with a great many features, but in contrast to libraries like Lodash , it doesn’t allow you to cherry-pick the ones you need. Rather, you always have to load the entire library.
Another common complaint is that the moment object is mutable. This can leads to confusion among developers. Consider:
What would you expect to be logged to the console? Unfortunately, the answer is “in 7 days” (and not “a few seconds ago”), because the code today.add(7, 'days') mutated the moment object, setting it to seven days in the future.
This can be avoided by cloning the moment object before preforming any date math, but by the time you remember to do that, the chances are you’ve already spent quite some time debugging.
A Light-weight Alternative
For those of you looking for a lighter alternative, consider date-fns . Date-fns is immutable, always returning a new date instead of changing the one you pass in. It has a simple API, is the perfect companion for Webpack and with its function-per-file style you can pick just what you need.
Moment.js is really an awesome library that simplifies date and time-related manipulations and validations. In this article, we focused on some of the features of Moment.js which help in parsing, validating, and manipulating dates and times in the browser and Node.js applications. A number of useful plugins are also available for Moment.js. Plugins like ISO Calendar, Jalaali Calendar, and many more can be found on the official plugin page . For more on Moment.js, the reader is directed to the library’s documentation .
FAQs About Moment.js
How to use moment.js.
What is the ISO time format for Moment?
In Moment.js, you can format a date and time in ISO 8601 format using the toISOString() method. The ISO 8601 format represents date and time information in a standardized way.
How do you convert a Moment object to Date object?
How do you get the current date in Moment?
To get the current date and time using Moment.js, you can simply call the moment() function without passing any arguments.
How do you increment a date with Moment?
To increment a date using Moment.js, you can use the add() method. The add() method allows you to add or subtract time units (such as days, months, years, etc.) to a Moment.js object.
How to Create a Date Object
Get the current date and time, get a date and time with individual values.
The syntax is Date(year, month, day, hour, minute, second, millisecond) .
Note that the months are zero-indexed, beginning with January at 0 and ending with December at 11.
Get a date and time from a timestamp
new Date(ms) returns the date of the epoch plus the number of milliseconds you pass in. In a day there's 86,400,000 milliseconds so:
will return Friday, January 2nd, 1970 (UTC).
Get a date and time from a string
Getting the date this way is very flexible. All of the examples below return valid Date objects:
You can also use the Date.parse() method to return the number of milliseconds since the epoch (January 1st, 1970):
Setting a time zone
This can lead to errors where the date returned is off by many hours. To avoid this, pass in a time zone along with the string:
You can also pass some, but not all, time zone codes:
Date Object Methods
Often you will not need the entire date, but just part of it like the day, week or month. Fortunately there are a number of methods to do just that:
Make Working with Dates Easier with Moment.js
Getting dates and times right is no small task. Every country seems to have a different way of formatting dates, and accounting for different time zones and daylight savings/summer time takes, well, a whole lot of time. That's where Moment.js shines – it makes parsing, formatting, and displaying dates a breeze.
To start using Moment.js, install it through a package manager like npm , or add it to your site through a CDN. See the Moment.js documentation for more details.
Get the current date and time with Moment.js
Get a date and time from a timestamp with Moment.js
Similar to new Date(ms) , you can pass the number of milliseconds since the epoch to moment() :
If you want to get a date using a Unix timestamp in seconds, you can use the unix() method:
Get a date and time from a string with Moment.js
ISO 8601 strings are recommended since it is a widely accepted format. Here are some examples:
Setting a time zone with Moment.js
However, to set a time zone, you must first get the Moment object in UTC mode:
Then you can adjust for the difference in time zones with the utcOffset() method:
You can also set the UTC offset as a number or a string:
To use named time zones ( America/Los_Angeles ) or time zone codes ( PDT ) with Moment objects, check out the Moment Timezone library.
Format the date and time with Moment.js
Here's a table with some common formatting tokens:
See the Moment.js docs for more formatting tokens.
If this article was helpful, share it .
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
- PyQt5 ebook
- Tkinter ebook
- SQLite Python
- wxPython ebook
- Windows API ebook
- Java Swing ebook
- Java games ebook
- MySQL Java ebook
last modified October 18, 2023
In this article we work with Moment.js in a Node application. There is a similar Day.js library, which is covered in Day.js tutorial .
Setting up Moment.js
First, we install Moment.js.
We initiate a new Node application.
We install Moment.js with npm i moment command.
Moment.js today's date
In the first example, we get today's date with Moment.js.
The example prints today's date and time.
We load the Moment.js library.
We get the current local datetime object with moment .
We format the output with format . By default, we get a long datetime format.
This is the ISO standard format. The date and time parts are separated by T character. The string is ended with a time zone.
Creating Moment.js objects
We can use several ways to create date and time Moment.js objects. These objects have to be formatted later to human-readable format.
The example creates date and time objects in five different ways.
We create a moment object from a string.
Here a moment object is created from an array.
We can use JSON objects to create moment objects.
We use a unix time stamp (in milliseconds) to define a moment object.
Moment.js formatting datetime
Moment.js objects are formatted with the format function. There are also options for localized formats.
The example formats date and time using Moment's format function.
Moment.js calculating datetime difference
With the diff function, we can calculate the difference between two datetime objects.
The example calculates the difference between two moment objects in days and hours.
The second parameter tells that the output will be in days.
The Battle of Borodino was a battle fought on 7 September 1812 in the Napoleonic Wars during the French invasion of Russia.
In the example, we calculate the number of days passed since then.
Moment.js datetime arithmetic
The add function is used to add date and time to the moment object and the subtract function subtract date and time from the moment object.
In the example, we add three days and subtract two years.
The second parameter of the add and subtract methods is the unit type.
Moment.js datetime parts
In the following example, we get the parts of the current datetime.
The example computes the current datetime. We get the year, month, date, hour, minute, second, and millisecond parts of the datetime.
Moment.js day of week, month, year
The following example calculates the day of week, month, and year.
The weekday returns the day of week, the date returns the day of month, and the dayOfYear returns the day of year.
Moment.js week of year, quarter, weeks in year
In the following example, we get the week of the year, the quarter of the year, and the number of weeks in the year.
The week method returns the week of the year, the quarter returns the quarter of the year, and the weeksInYear returns the number of weeks in the year.
Moment.js relative datetime
We can compute relative datetime with fromNow , startOf , and endOf functions.
The example uses the aforementioned functions.
Here we calculate the number of days which have passed since the beginning of the year.
These lines calculate the number of minutes till midnight.
Here we get the number of years until the specified day.
Moment.js checking validity
We can use the isValid method to check if the date and time object is valid.
The example checks the validity of two days.
Moment.js date queries
The isBefore and isAfter functions can be used to determine if a date is before or after another date.
In the example, we compare three dates using isBefore and isAfter functions.
The isBetween function checks if a date is in the given date range.
The example uses the isBetween function to determine if a date is within the specified date range.
Moment.js unix time
Unix time is the number of seconds since the Unix epoch. The unix function returns the value of time in seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time.
In the example, we get the current Unix time and convert Unix time 1 s to human readable format.
We get the Unix time with unix function. The returned value is the number of seconds elapsed from the start of the Unix Epoch.
We get the unix time of 1 s and output it in the given format.
Moment.js parsing date and time
We can parse a string representation of date and time by passing the date and time format to the moment function.
In the example, we parse a non-standard date and time string. We pass the expected format as a second parameter of the moment function.
Moment.js localized date and time
With the locale function, we can set the locale in which we get the output.
In the example, we print the current moment in three different locales.
We have Slovak, German, and Hungarian date and time outputs of the current moment.
Our planet is a sphere; it revolves round its axis. The Earth rotates towards the east, so the Sun rises at different times in different locations. The Earth rotates once in about 24 hours. The world was therefore divided into 24 time zones. In each time zone, there is a different local time. This local time is often further modified by the daylight saving.
There is a pragmatic need for one global time. One global time helps to avoid confusion about time zones and daylight saving time. The UTC (Universal Coordinated time) was chosen to be the primary time standard. UTC is used in aviation, weather forecasts, flight plans, air traffic control clearances, and maps. Unlike local time, UTC does not change with a change of seasons.
The example prints the current UTC time and the local time.
The universal time is retrieved with utc .
In our case, the difference between the local and universal time is two hours. One hour is for the time zone and another hour for the daylight saving.
Moment.js leap year
A leap year is a year containing an additional day. The reason for an extra day in the calendar is the difference between the astronomical and the calendar year.
In the example, we have an array of years. We determine which years are leap years.
We determine if a year is a leap year with the isLeapYear function.
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
Posted on Jan 2, 2023 • Originally published at techdevblog.io on Jan 2, 2023
In this tutorial, we'll take a look at the top 10 things you need to know to get started with Moment.js and start using it to its full potential in your projects.
The first thing you need to do to start using Moment.js is to install it in your project. There are a few different ways to do this, depending on how you want to use it.
One option is to download the Moment.js library file and include it in your project using a script tag:
Alternatively, you can use a package manager like npm or Yarn to install Moment.js as a dependency in your project:
Once you have Moment.js installed, you're ready to start using it in your project.
To parse a date with Moment.js , you can use the moment() function and pass it the string representation of the date you want to parse. For example:
Once you have a moment object, you can use it to display the date in any format you like. To display a moment object as a string, you can use the format() method and pass it a string specifying the desired format.
Here are a few examples of using the format() method:
You can use a variety of tokens to specify the exact format you want. For a full list of available tokens, check out the Moment.js documentation .
One of the most powerful features of Moment.js is the ability to easily manipulate dates. You can use the add() and subtract() methods to add or subtract time from a moment object. For example:
You can also use the startOf() and endOf() methods to set the moment object to the start or end of a specific unit of time. For example:
In addition to working with dates and times, Moment.js also includes a duration object that you can use to represent a length of time. To create a duration object, you can use the duration() function and pass it a number of milliseconds.
Here's an example of creating and working with a duration object:
You can also use the add() and subtract() methods to add or subtract time from a duration object.
Moment.js includes a variety of query methods that you can use to check the value of a moment object. For example, you can use the isBefore() and isAfter() methods to check if a moment object occurs before or after another moment object:
You can also use the isSame() method to check if a moment object occurs at the same time as another moment object:
One of the great things about Moment.js is that it supports localization, which means that you can use it to display dates and times in different languages and formats. To use localization with Moment.js , you'll need to include the appropriate locale file in your project and use the locale() method to set the locale.
For example, here's how you would set the locale to French:
With the French locale set, the format() method will automatically display dates and times in the appropriate French format.
In addition to localization, Moment.js also supports working with time zones. To work with time zones, you'll need to include the moment-timezone library in your project and use the tz() method to specify the time zone you want to work with.
For example, here's how you would set the time zone to Pacific Standard Time:
With the time zone set, the format() method will automatically display dates and times in the appropriate time zone.
One of the great things about Moment.js is that it has a large and active community of developers who have created a variety of plugins that you can use to extend the functionality of the library.
As you start using Moment.js in your projects, there are a few best practices to keep in mind:
- Always use the same time zone for all dates and times in your application. This will make it easier to work with dates and times and avoid confusion.
- Use the utc() method to create moment objects that are independent of the local time zone. This can be useful if you're storing dates and times in a database and want to avoid issues with daylight saving time.
- Use the clone() method to create a copy of a moment object instead of modifying the original object. This will help you avoid unexpected side effects and make your code easier to debug.
- Consider there may be better alternatives to Moment.js for your project, such as Luxon .
By following these best practices, you'll be able to get the most out of Moment.js and use it effectively in your projects.
Top comments (0)
Templates let you quickly answer FAQs or store snippets for re-use.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .
Hide child comments as well
For further actions, you may consider blocking this person and/or reporting abuse
Throttling ⏱️ vs Debouncing ⏳: Boost Performance for your React app 🚀
Fidal Mathew - Feb 22
React 19: A Deep Dive into the Upcoming Major Release
Ashish Patel - Feb 22
How to Build a Tailwind CSS Progress Bar
HyperCode - Feb 13
#100DaysOfCode with Daily Web Frontend Challenges
BigsonDev - Feb 12
Once suspended, tech-dev-blog will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, tech-dev-blog will be able to comment and publish posts again.
Once unpublished, all posts by tech-dev-blog will become hidden and only accessible to themselves.
If tech-dev-blog is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to Matt Williams.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community safe. Here is what you can do to flag tech-dev-blog:
tech-dev-blog consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.
Unflagging tech-dev-blog will restore default visibility to their posts.
We're a place where coders share, stay up-to-date and grow their careers.
Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →
- Product Management
- Solve User-Reported Issues
- Find Issues Faster
- Optimize Conversion and Adoption
- Start Monitoring for Free
It’s almost 2018! We use dates and time every day of our lives, I just did, and if you are a developer designing a product, tool, or service, you most likely would need to manipulate date in whatever you are building.
Moment can be run on both the browser as well as on the server-side. Using Node.js on the server-side, moment is installed via npm by running this on the command line:
moment can then simply be required:
We just created the moment object, which can be manipulated to return any desired date value. Once the moment function is called with moment() it defaults to the current date, just like new Date() .
In the browser, moment is dowloaded here and included in a script tag like this:
Alternatively, it can be imported from a CDN and used as a source in script tags. Other installation methods can be found here .
Manipulating date and time
The moment object gives us the ability to manipulate the date object however we choose, applying several (chaining) moment methods to it returns desired formatted date values.
For example, we get the following format with new Date() :
What if in our use-case, it’s more intuitive to show the user a relative date? With moment, you can simply do this:
Calling moment() without any parameters returns the current date in your timezone.
Let’s go in-depth with more formatting approaches that Moment offers.
Previously, formatting dates with the Date() string involved performing several string operations on the returned date string. With moment we just need to add the format() method to format the date. This method also receives parameters defining how we would like the date to appear.
To get a particular moment as a string, pass the string value as a parameter when calling moment() .
The format of the date specified can also be passed in as a parameter if known. The date is treated as invalid if its values cannot be parsed.
Others date formats can be found here .
moment uses method chaining to do awesome manipulations when a moment is called, for instance:
This is just an illustration of chaining methods in moment . Also note that moments are mutable and therefore change the original fetched moment . To create a new manipulated moment , the original moment can be cloned into a new variable.
Over 200k developers use LogRocket to create better digital experiences
This method subtracts time from the original moment. Here, the subtract() method is called and passed parameters of a number denoting the amount of time to be removed and the time value. This time value can also be written in shorthand, they include:
- Q: Quarters
- Ms: Milliseconds
Multiple combinations can also be done with the subtract time method by chaining.
This is similar to the subtract() method and only adds a desired amount of time to the moment .
This method mutates the moment to the start of a specified time. This sets the time to the beginning of the current time, either to the beginning of the day, month, year, or minute.
This is the opposite of startOf() and mutates the moment to the end of a unit of time. This includes the week, month, day, or year.
Time from now
This displays relative time is used to give a whole picture of the difference between two timeframes.
The fromNow() method also takes a boolean, passing in true removes the ‘ago’ suffix.
To view the exact time from a particular date, the from() method is used.
More great articles from LogRocket:
- Don't miss a moment with The Replay , a curated newsletter from LogRocket
- Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
- Use React's useEffect to optimize your application's performance
- Switch between multiple versions of Node
- Discover how to use the React children prop with TypeScript
- Explore creating a custom mouse cursor with CSS
- Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Time to now
Similar to fromNow() , the toNow() method returns the opposite of the fromNow() method. The to() method is also used to show relative time between two time values.
This is one of the common problems encountered when manipulating time and date. With moment , the diff() method is used to calculate the difference between two moments and it returns the difference in milliseconds. However, other units of time such as years, months, weeks, days, hours, minutes, and seconds can be returned. The diff() method takes in a unit of time as a first parameter and can take the desired time unit as a second parameter.
These are moment methods that return boolean values and is used to compare two date values.
As its name implies, the isBefore() method verifies if one date value is before another date value.
Similar to the isBefore() method, this method verifies if a date after is after another date value and returns either true or false .
Other query methods used in comparing two date values include:
These methods all follow the same syntax and return true or false . There are also methods which verify the validity of a certain date. These are:
The isDST() verifies if the moment is in Daylight Saving Time or not.
The isLeapYear() method verifies if a year is a leap year and returns a boolean.
With the isValid() method, the validity of a moment can be ascertained.
In this article, we have seen how moment make date and time handling and management seamless. By simply applying methods on the moment object either singularly or in chains we can effectively manipulate our date and time to achieve desired results.
Find additional resources here on the official moment.js documentation .
- Click to share on Twitter (Opens in new window)
- Click to share on Reddit (Opens in new window)
- Click to share on LinkedIn (Opens in new window)
- Click to share on Facebook (Opens in new window)
Stop guessing about your digital experience with LogRocket
Using CRDTs to build collaborative Rust web applications
CRDTs, or conflict-free replicated data types, is a concept that underlies applications facing the issue of data replication across a […]
Guide to using TensorFlow in Rust
We explore the fusion of TensorFlow and Rust, delving into how we can integrate these two technologies to build and train a neural network.
Using SignalDB with React: A complete guide
SignalDB enables automatic data synchronization between your components and a local in-memory or persistent database.
A guide to Next.js layouts and nested layouts
Understanding how layouts, nested layouts, and custom layouts work in Next.js is crucial for building complex, user-friendly projects.
Leave a Reply Cancel reply
- NodeJS Tutorial
- NodeJS Exercises
- NodeJS Assert
- NodeJS Buffer
- NodeJS Console
- NodeJS Crypto
- NodeJS File System
- NodeJS Globals
- NodeJS HTTP
- NodeJS HTTP2
- NodeJS Path
- NodeJS Process
- NodeJS Query String
- NodeJS Stream
- NodeJS String Decoder
- NodeJS Timers
- NodeJS Interview Questions
- NodeJS Questions
- Web Technology
- Solve Coding Problems
- Moment.js moment().utc() Method
- Moment.js moment().min(Moment|String|Number|Date|Array) Method
- Moment.js moment().max(Moment|String|Number|Date|Array) Method
- Moment.js moment().endOf() Method
- Moment.js moment().startOf() Method
- Moment.js moment().local() Method
- Moment.js moment().zone() Method
- Moment.js moment().subtract() Method
- Moment.js Customize Weekday Abbreviations
- Moment.js using with System.js
- Moment.js using with Browser
- Moment.js using with Typescript
- Moment.js moment().toObject() Method
- Moment.js moment().weekday(Number) Method
- Moment.js moment().max() Method
- Moment.js moment().min() Method
- Moment.js moment().get() Method
- Moment.js moment().year() Method
- Moment.js moment().weeksInYear() Method
Moment.js moment().add() Method
The moment().add() method is used to add the given unit of time to the Moment object. The unit can be specified in all the recognized variations of the unit including its plural and short forms.
Parameters: This method accepts multiple parameters as mentioned above and described below:
- Number: It is a number that denotes the time value that has to add.
- String: It is a string that denotes the unit of time that has to be added.
- Duration: This is a Duration object that contains the time that needs to be added.
- Object: It is an object that can be used to denote all the time values that can be added to the Moment.
Return Value: This method returns a string of the given unit of time from the Moment object.
Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.
Moment.js can be installed using the following command:
Installation of moment module:
The below examples will demonstrate the Moment.js moment().add() Method .
Please Login to comment...
- Web Technologies
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- MomentJS Tutorial
- MomentJS - Home
- MomentJS - Overview
- MomentJS - Environment Setup
- MomentJS - Introduction
- MomentJS - Parsing Date And Time
- MomentJS - Date Validation
- MomentJS - Getter/Setter
- Manipulate Date And Time
- Formatting Date And Time
- MomentJS - Date Queries
- MomentJS - Internationalization
- MomentJS - Customization
- MomentJS - Durations
- MomentJS - Utilities
- MomentJS - Plugins
- MomentJS - Examples
- MomentJS Useful Resources
- MomentJS - Quick Guide
- MomentJS - Useful Resources
- MomentJS - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
MomentJS - Add
This method allows you add days, time, years, hours, seconds etc., on the moment object.
Using the add method we can add number, hours, days etc.
The following table shows the lists of keys/shorthand which you can use with add method.
You can make use of key or shorthand unit inside the add method as follows −
Let see a working example which shows to add days to the current date using add method.
Note that the above code displays the current date and the date after adding 5 days to it.
You can also use the key with add method as follows −
Let see an example which adds 5 hours to the given date −
If there are multiple additions to be done to the date, you can do it using add method chaining or using object literal.
Add Method using Chaining
Consider you want to add days and months to the current date. It can be done using method chaining as shown in below example −
To add days and months to the current date, we can use method chaining as follows −
We can also use key as shown in the code given below −
Add Method using Object
Using this technique, you can use object literal for adding multiple keys to the current date.
The object method is used as follows −
You can also use keys in the object form as follows −
In case, we need to add days or months to a given date, the same can be done as shown below −
We have added 5 days and 2 months to the date 10/10/2014 which gives the output as 15/01/2015.
Adding Duration to Add Method
We can also use duration method to add days, months, years, time etc. to a given date.
Observe the following example that shows how to add 5 weeks to a given date using duration −
Note that we have added 5 weeks to 31/01/2012 and thus the output is as follows −
Special Cases for Months and Years
In case we are trying to add months to the date whose days are greater than the months added, it will take the last day of the month which is added to the date.
In the above example, we are adding one month to 31/01/2017, now since February has 28 days it takes the last day of February and displays the date as shown below −
how to add days in moment js?
- Example in reactjs
Hi Friends 👋,
Welcome To Infinitbility! ❤️
To add days in the date using moment js, just use the moment().add() method by passing two parameters, first is the number of days you want to add, and the second parameter is 'days' it’s means want to add days.
Just import moment in your file and invoke moment().add(30, 'days'); it will show the current date time plus 30 days.
Today, I’m going to show How do I add days in moment js, here I will use the momentjs common method add() to add days in the date object.
Let’s start the today’s tutorial How do you add days in the date using moment js?
Table of content
Use the below installation command as per your package manager, moment support npm, Yarn, NuGet, spm, and meteor.
Example in reactjs #
In the following example, we are going to do
- import the moment package
- create a function and console the current time.
- add days in the current time and re-console it.
let’s write the code.
In the above program, we call moment().add() in simple custom function and and add 30 days in it.
let’s check the output.
I hope it’s help you, All the best 👍.
Fast 2kB alternative to Moment.js with the same modern API
If you use Moment.js, you already know how to use Day.js.
All API operations that change the Day.js object will return a new instance instead.
This helps prevent bugs and avoid long debugging sessions.
Day.js has great support for internationalization. But none of them will be included in your build unless you use them.
Moment Timezone Documentation
Where to use it.
To use moment-timezone, you will need [email protected] + , moment-timezone.js , and the moment-timezone data.
For convenience, there are builds available on momentjs.com/timezone/ with all the zone data or a subset of the data.
- moment-timezone-with-data.js is recommended for server environments (Node.js) and covers all years available.
- moment-timezone-with-data-10-year-range.js is recommend for most browser environments, covering +/- 5 years from the year published.
- moment-timezone-with-data-1970-2030.js covers a 60 year range, for those that need more data but not the larger file size of the full data file.
If you use one of the above files, you still need moment.js , but you do not need moment-timezone.js because it is included.
In Node.js, all the data is preloaded. No additional code is needed for loading data.
In ECMAScript native module format (or in TypeScript):
Note: You don't need to require/import the base moment library as well. Moment Timezone will automatically load and extend the moment module, then return the modified instance.
Package managers like npm and yarn can sometimes create situations where multiple versions of moment are installed. Importing only from moment-timezone can help ensure that the same version is used consistently. See this comment on issue #982 for a much more detailed explanation, including steps to fix potential versioning problems.
The pre-built bundles are also included in the npm package, and can be loaded directly. These allow you to import the library with a smaller subset of data.
You can also import just the library without any preloaded data.
When using Moment Timezone in the browser, you will need to load the data as well as the library.
You can either use the prebuilt library and data files linked on the homepage or build a subset of the data yourself and load it .
Note: By default, webpack bundles all moment-timezone data (in moment-timezone 0.5.25, that’s over 900 KBs minified). To strip out unwanted data and bundle only the zone and date range data you need, add the moment-timezone-data-webpack-plugin package:
Alternatively, the pre-built bundles are also included in the npm package, and can be loaded directly. See the Node.js section for more details.
Also see the primary Moment.js Webpack documentation for an example of how to reduce Moment’s bundled locale data. Together these techniques can significantly reduce the final bundle size (by over 1 MB minified, or 85 KB minified + gzipped).
Using Time zones
There are two interfaces for using time zones with Moment.js.
moment.tz(..., String) does parsing in given time zone
It takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier:
Note that created moments have different UTC time because these moments were created in different time zones.
moment().tz(String) does converting to provided time zone
In this example, you first create moment.utc("2013-11-18 11:55") object in UTC, and then change its timezone to specified. This also works if you create the object in your default timezone: moment("2013-11-18 11:55") .
Note that created moments have equal UTC time because these moments were created in a default timezone .
Due to daylight saving time, there is a possibility that a time either does not exist, or has existed twice.
In the spring, at the start of DST, clocks move forward an hour. In reality though, it is not time that is moving, it is the offset moving.
Moving the offset forward gives the illusion that an hour has disappeared. As the clock ticks, you can see it move from 1:58 to 1:59 to 3:00 . It is easier to see what is actually happening when you include the offset.
The result is that any time between 1:59:59 and 3:00:00 never actually happened. Moment Timezone accounts for this. If you try to parse a time that never existed, it will skip forward by the amount of the DST gap (usually 1 hour).
In this example, the two o'clock hour doesn't exist, so it is treated as equivalent to the three o'clock hour.
In the fall, at the end of DST, clocks move backward an hour. Again, time is not moving backwards, only the offset is. In this case, the illusion is that an hour repeats itself.
Again, it is easier to see what is actually happening when you include the offset.
Moment Timezone handles this by always using the earlier instance of a duplicated hour.
You won't be able to create a moment with the later instance of the duplicated hour unless you include the offset when parsing.
Converting to Zone
The moment#tz mutator will change the time zone and update the offset.
This information is used consistently in other operations, like calculating the start of the day.
Without any argument, moment#tz returns:
- the time zone name assigned to the moment instance or
- undefined if a time zone has not been set.
On passing a second parameter as true , only the timezone (and offset) is updated, keeping the local time same. Consequently, it will now point to a different point in time if the offset has changed.
In addition to including the +00:00 formatting information, Moment Timezone also includes information for the abbreviated time zone name.
Note that these abbreviations may change depending on the time zone offset. This helps to distinguish offsets between places that may or may not use DST.
Note also that these abbreviations are not globally unique. Below, you can see that both United States Central Standard Time and China Standard Time have the same abbreviation.
You can also use moment#zoneAbbr to get the zone abbreviation. This is what moment.js uses when formatting the z token.
Moment.js also provides a hook for the long form time zone name. Because these strings are generally localized, Moment Timezone does not provide any long names for zones.
To provide long form names, you can override moment.fn.zoneName and use the zz token.
Please note that the z formatting token will not always show the abbreviated time zone name, instead, will show the time offsets for each region.
Default time zone
By default, moment objects are created in the local time zone. The local time zone is determined by your JS environment such as a browser or server like Node.js.
To change the default time zone, use moment.tz.setDefault with a valid time zone.
To reset the default time zone to local, use moment.tz.setDefault with no arguments.
This is a global setting (shared by all modules).
Subsequent calls to moment.tz.setDefault will not affect existing moment objects or their clones.
Guessing user zone
Moment Timezone uses the Internationalization API ( Intl.DateTimeFormat().resolvedOptions().timeZone ) in supported browsers to determine the user's time zone.
On other browsers, time zone detection is rather tricky to get right, as there is little information provided by those browsers. For those, it will use Date#getTimezoneOffset and Date#toString on a handful of moments around the current year to gather as much information about the browser environment as possible. It then compares that information with all the time zone data loaded and returns the closest match. In case of ties, the time zone with the city with largest population is returned.
By default Moment Timezone caches the detected timezone. This means that subsequent calls to moment.tz.guess() will always return the same value.
You can call moment.tz.guess() with an optional boolean argument "ignoreCache". If set to true, the cache will be ignored and overwritten with the new value.
Getting all Zones
To get a list of all available time zone names, use moment.tz.names .
Getting Zones for country
To get a list of time zones for some country, use moment.tz.zonesForCountry() .
By default this method returns zone names sorted alphabetically:
To get also offsets, pass true as 2nd parameter:
it returns array of objects with name and offset:
It's useful if you need to sort time zones by offset.
All country codes can be retrieved using method moment.tz.countries()
In order to match a timestamp to an offset, Moment Timezone uses a Zone object.
Though you shouldn't even need to use it, this object's constructor is available on the moment.tz.Zone namespace.
This object has 5 properties.
The uniquely identifying name of the time zone. See the IANA Time Zone database naming guidelines for more details about the naming convention.
Note that the guidelines also say that these zone identifiers shouldn't be displayed directly to end users:
Inexperienced users are not expected to select these names unaided. Distributors should provide documentation and/or a simple selection interface that explains each name via a map or via descriptive text like "Czech Republic" instead of the timezone name "Europe/Prague" .
Providing a full list of translated zone names for every locale is outside the scope of Moment Timezone. The Unicode CLDR project contains locale-aware mappings for this purpose.
Get the abbreviation for a given timestamp (in milliseconds) from a Zone .
Get the offset for a given timestamp (in milliseconds) from a Zone .
POSIX compatibility requires that the offsets are inverted. Therefore, Etc/GMT-X will have an offset of +X and Etc/GMT+X will have an offset of -X . This is a result of IANA's Time Zone Database and not an arbitrary choice by Moment.js. Thus, using locality based identifiers is preferred over fixed-offset identifiers.
This is also described on the Wikipedia entry for the database :
The special area of "Etc" is used for some administrative zones, particularly for "Etc/UTC" which represents Coordinated Universal Time . In order to conform with the POSIX style, those zone names beginning with "Etc/GMT" have their sign reversed from the standard ISO 8601 convention. In the "Etc" area, zones west of GMT have a positive sign and those east have a negative sign in their name (e.g "Etc/GMT-14" is 14 hours ahead of GMT).
For example, using the Europe/Madrid identifier gives a different result from Etc/GMT+1 .
Parse an offset for a timestamp constructed from Date.UTC in that zone.
This is what Moment Timezone uses to parse input into a time zone. The process is conceptually similar to the following.
Assume we want to find the exact moment of March 19 2014 8:30 am in New York. Because the offset varies between -04:00 and -05:00 in New York, we don't know what the offset was on March 19th.
Instead, we create a timestamp in UTC and pass that to zone.parse , which will return the offset at that time.
This is the code that handles the cases referenced in the Parsing Ambiguities section above.
Moment Timezone uses two data formats. An unpacked version for calculations and a packed version for minified transport.
The unpacked format looks exactly like the zone object .
The data below is for Los Angeles between 2014 and 2018.
The lengths of abbrs, untils, offsets are all the same. The offset and abbr at any index are only active while the timestamp is less than the until at that index.
An easy way to read this aloud is "between untils[n-1] and untils[n] , the abbr should be abbrs[n] and the offset should be offsets[n] " .
Note that untils are measured in milliseconds and offsets are measured in minutes.
The packed format represents an unpacked zone in a single string.
The data below is for Los Angeles between 2014 and 2018. More time zones can be seen in the packed source file .
In order to save as many bytes as possible, we used a very compact format to store the data.
The data is split into 6 sections separated by pipes.
Name: The canonical name of the time zone.
Abbr Map: A space separated list of all the abbreviations ever used in this time zone.
Offset Map: A space separated list of all the offsets ever used in this time zone in minutes in base 60.
Abbr/Offset Index: A tightly packed array of indices into the offset and abbr maps. These are also in base 60.
Timestamp Diffs: This is where the timestamps are stored.
Because we are dealing with a sorted list of timestamps, we just store the diff from the last timestamps rather than storing the full timestamps.
The first item in the array is a unix timestamp in minutes. All items after the first item are numbers of minutes to be added to the previous value during unpacking. All items are stored in base 60.
As you may have seen from the example above, the timestamp diffs tend to duplicate the same values from year to year. These duplications allow gzip to compress the data even further than if we used full timestamps.
Population: The rough population size of the city that the zone is named after.
This is not in base 60, but instead uses scientific exponential notation. For example, a value of 15e6 means 15 * 10 6 (that's 15 with 6 zeros after it) and therefore represents the number 15,000,000 .
The value is only used to compare nearly-identical zones when using the guess feature , so it doesn't need to be precise.
Note that this value might be empty for some zones.
You may be wondering why base 60 is used. Base 62 is a fairly common tool for ascii data compression, using a-z to represent 10-35 and A-Z to represent 36-61 .
While it may have saved a few bytes to use base 62, much of the data in Moment Timezone maps nicely to multiples of 60.
There are 60 minutes in an hour and 60 seconds in a minute. 3 hours is 30 minutes in base 60 and 300 seconds in base 60 instead of 180 and 10800 in base 10 or 2U and 2Oc in base 62.
In order to reduce duplication, the Moment Timezone data packer will create links out of two zones that share data that is exactly the same.
This data is the two zone names separated by a pipe.
Once the data has been packed and transported to the client, it must be added to Moment Timezone.
This happens automatically in Node.js and the pre-built bundles . If you're using a different loading method you might need to load the data yourself.
Adding a Zone
To add zone data to Moment Timezone, use moment.tz.add .
To add more than one zone, pass an array of packed data.
Note: The above zone data is sample data and is not up to date. Reference the moment-timezone source for up to date data.
Adding a Link
To link two zone names to the same data, use moment.tz.link .
The strings passed in should be in the link format : the two zone names separated by a pipe.
To add more than one link at a time, pass an array of link strings.
Loading a Data Bundle
The data for Moment Timezone comes from the IANA Time Zone Database . New versions are released periodically as time zone laws change in various countries.
The versions are named after the year and an incrementing letter. 2014a 2014b 2014c...
In order to keep versions together, Moment Timezone has a bundled object format as well.
To load a bundle into Moment Timezone, use moment.tz.load .
Checking Zone Existence
To check if a zone exists, use moment.tz.zone . It will return the Zone if it was loaded and null if it was not loaded.
Getting Zone Names
Because of the complexity of the packed and unpacked data formats, Moment Timezone has some heavily tested utility functions for working with the data.
Methods for unpacking data are included with the core library, as they are needed in order to use the library.
Methods for packing and subsetting the data are included in an additional moment-timezone-utils.js file. This file adds some more methods to the moment.tz namespace.
This converts data in the unpacked format to the packed format .
This converts data in the packed format to the unpacked format .
Pack Base 60
Convert a base 10 number to a base 60 string.
Much like Number.prototype.toFixed , moment.tz.packBase60 accepts a second argument for the number of digits of precision.
A solitary 0 before the decimal point is dropped.
Trailing zeroes after the decimal point are dropped.
Unpack Base 60
Convert a base 60 string to a base 10 number.
In order to reduce duplication, we can create links out of two zones that share data.
This is especially useful when combined with moment.tz.filterYears , as older rules that would have differentiated two Zones may not be in the filtered year range, allowing them to be linked to save space.
By default, Moment Timezone includes all the data from the IANA Time Zone Database . This includes data from at least 1900 to 2038. Releases from version 0.5.37 onward include even more data, beyond the year 2400. The data for all these years may not be necessary for your use case.
moment.tz.filterYears can be used to filter out data for years outside a certain range.
If only one year is passed, it will be used for the start and end year.
Alternatively, one of the smaller pre-built bundles available on the homepage might already fit your needs.
Filter Years, Create Links, and Pack
The packing, link creation, and subsetting of years are all tools for compressing data to be transported to the client.
The moment.tz.filterLinkPack method combines all these into one simple interface. Pass in an unpacked bundle, start year, and end year and get a filtered, linked, packed bundle back.
This is what is being used to compress the output for the bundled data + library files on the homepage .