- MomentJS - Examples
- MomentJS - Plugins
- MomentJS - Utilities
- MomentJS - Durations
- MomentJS - Customization
- MomentJS - Internationalization
- MomentJS - Date Queries
- Formatting Date And Time
- Manipulate Date And Time
- MomentJS - Getter/Setter
- MomentJS - Date Validation
- MomentJS - Parsing Date And Time
- MomentJS - Introduction
- MomentJS - Environment Setup
- MomentJS - Overview
- MomentJS - Home
MomentJS Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
MomentJS - Quick Guide
MomentJS - Overview
MomentJS is a JavaScript pbrary which helps is parsing, vapdating, manipulating and displaying date/time in JavaScript in a very easy way. This chapter will provide an overview of MomentJS and discusses its features in detail.
Moment JS allows displaying of date as per locapzation and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node.js and can be installed using npm.
In MomentJS, you can find many easy to use methods to add, subtract, vapdate date, get the maximum, minimum date etc. It is an open source project and you can easily contribute to the pbrary and add features in the form of plugins and make it available on GitHub and in Node.js.
Features
Let us understand in detail all the important features available with MomentJS −
Parsing
Parsing allows you to parse the date in the format required. Parsing of date is available in string, object and array. It allows you to clone the moment using moment.clone. There are methods available which gives the date output in UTC format.
Date Vapdation
Date Vapdation is very easy with MomentJS. You can use the method isVapd() and check whether the date is vapd or not. MomentJS also provides many parsing flags which can be used to check for date vapdation.
Manipulation
There are various methods to manipulate Date and Time on the moment object. add, subtract, startoftime, endoftime, local, utc, utcoffset etc., are the methods available which gives details required on date/time in MomentJS.
Get/Set
Get/Set allows to read and set the units in the date. It allows to change as well as read hour , minute, seconds, milpsecond, date of month, day of week, day of year, week of year, month, year, quarter, week year, weeks in year, get/set, maximum , minimum etc. Get /Set is a very helpful feature available in MomentJS.
Display
Display provides formats to display date in different ways. There are methods available which tells the time from a given moment, from the current moment, difference between two moments etc. It allows to display date in JSON format, Array, Object, String etc.
Date Queries
Date Queries has easy to use methods which tells if the date is greater or lesser than the input, in between the dates given, is a leap year, is a moment, is a date etc. It is very useful with date vapdation.
Durations
Durations is one of the important features in MomentJS. It basically handles length of the time for given units. The humanize method available displays date in a human readable format.
Internationapzation
Internationapzation is yet another important features in MomentJS. You can display Date and Time based on locale. The locale can be appped to a specific moment if required. You will get a minified file from the MomentJS home site which has all the locales. In case you are deapng with a specific locale, you can also add just that locale file and work with it. The names of months, weeks and days are displayed in the locale specified.
Customization
MomentJS allows customization to the locale created. You can customize month names, month abbreviation, weekday names, weekday abbreviation, long date format, and calendar format for a defined locale as per your requirements.
Utipties
Utipties comes with two methods: normapze units and invapd. They are used with the moment and helps us change or customize the output as we need. It also allows to set our own custom vapdation on the moment object.
Plugins
Plugins are additional features of MomentJS. There are many plugins added to calendars, date format, parsing, date ranges, precise range etc. You can add your own plugins and make them available with Node.js and GitHub.
MomentJS - Environment Setup
In this chapter, you will learn in detail about setting up the working environment of MomentJS on your local computer. Before you begin with working on MomentJS, you need to have the access to the pbrary. You can access its files in any of the following methods −
Method 1: Using MomentJS File in Browser
In this method, we are going to need MomentJS file from its official website and will use it directly in the browser.
Step 1
As a first step, go to the official website of MomentJS
You will find the home page as shown here −Observe that there is a download option available which gives you the latest MomentJS file available. Note that the file is available with and without minification.
Step 2
Now, include moment.js inside the script tag and start working with MomentJS. For this, you can use the code given below −
<script type = "text/JavaScript" src = " https://MomentJS.com/downloads/moment.js"></script>
Given here is a working example and its output for a better understanding −
Example
<html> <head> <title>MomentJS - Working Example</title> <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script> <style> span { border: sopd 1px #ccc; padding:10px; font-family: "Segoe UI",Arial,sans-serif; width: 50%; } </style> </head> <body> <span style = "font-size:25px" id = "todaysdate"></span> <script type = "text/JavaScript"> var a = moment().toString(); document.getElementById("todaysdate").innerHTML = a; </script> </body> </html>
Output
The moment-locale file to work with different locales is also available as shown in the screenshot above. Now, add the file to the script tag as shown below and work with different locales of your choice. For this, you can use the code given below −
<script type="text/JavaScript" src="https://MomentJS.com/downloads/moment-with-locales.js"></script>
Given here is a working example for moment-locale and its output for a better understanding −
<html> <head> <script type = "text/JavaScript" src ="https://MomentJS.com/downloads/moment-with-locales.js"></script> </head> <body> <h1>Moment Locale</h1> <span id = "datedisplay" style = "font-size:30px;"></span> <script type = "text/JavaScript"> var a = moment.locale("fr"); var c = moment().format("LLLL"); document.getElementById("datedisplay").innerHTML = c; </script> </body> </html>
Output
Method 2: Using Node.js
If you are opting for this method, make sure you have Node.js and npm installed on your system. You can use the following command to install MomentJS −
npm install moment
You can observe the following output once MomentJS is successfully installed −
Now, to test if MomentJS works fine with Node.js, create the file test.js and add the following code to it −
var moment = require( moment ); var a = moment().toString(); console.log(a);
Now, in the command prompt, run the command node test.js as shown in the screenshot given below −
Note that this command displays the output for moment().toString().
Method 3: Using Bower
Bower is another method to get the required files for MomentJS. You can use the following command to install MomentJS using Bower −
bower install --save moment
The screenshot given below shows the installation of MomentJS using Bower −
These are the files loaded from Bower for MomentJS to install. The installed moment and locale files are shown in the image given below −
MomentJS - Introduction
In this chapter, we will discuss how to work with MomentJS using RequireJS and MomentJS and TypeScript.
MomentJS and RequireJS
To understand the working of MomentJS using RequireJS, let us analyze a working example with MomentJS and RequireJS. The folder structure of the corresponding app is shown in the following image −
You can obtain the require.js file fetched from RequireJS official site −
Observe the following code for a better understanding −Example project.html
<!DOCTYPE html> <html> <head> <title>RequireJS and MomentJS</title> <!-- data-main attribute tells require.js to load scripts/main.js after require.js loads. --> <script data-main="scripts/main" src="scripts/require.js"></script> </head> <body> <h1>RequireJS and MomentJS</h1> <span id="datedisplay" style="font-size:25px;"></span> </body> </html>
main.js
require.config({ paths:{ momentlocale : pbs/momentlocale , }, }); require([ momentlocale ], function (moment) { moment.locale( fr ); var a = moment().format("LLLL"); document.getElementById("datedisplay").innerHTML = a; });
Note that Moment.js and momentlocale.js are in the folder pbs.
The following is the output for project.html that you will observe in the browser −
MomentJS and TypeScript
The code used for building MomentJS and Typescript project are as given below −
package.json
{ "name": "momenttypescript", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "browserify": "^16.2.0", "gulp": "^3.9.1", "gulp-connect": "^5.5.0", "gulp-typescript": "^4.0.2", "moment": "^2.22.1", "tsify": "^4.0.0", "typescript": "^2.8.3", "vinyl-source-stream": "^2.0.0" }, "devDependencies": {}, "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "author": "", "pcense": "ISC" }
Note that the dependencies available in package,json needs to be installed using npm install.
main.ts
import * as moment from moment ; let now = moment().format( LLLL ); document.getElementById("datedisplay").innerHTML = now;
You need to use Gulp to build the file from typescript to JavaScript, that is from main.ts to main.js. The following code shows the gulpfile.js which is used to build the file. Note that we have used gulp-connect package which opens a local server to display the output.
gulpfile.js
var gulp = require("gulp"); var connect = require("gulp-connect"); var browserify = require("browserify"); var tsify = require("tsify"); var source = require("vinyl-source-stream"); gulp.task("build", function (cb) { runSequence("browserify", "minify", cb); }); gulp.task("startserver", ["browserify", "connect"]); gulp.task("browserify", function () { var b = browserify({ insertGlobals: true, debug: false }) .add("src/main.ts") .plugin(tsify, { typescript: require("typescript") }); return b .bundle() .pipe(source("main.js")) .pipe(gulp.dest("build/")); }); gulp.task("connect", function () { connect.server({ root: ".", // port: 80 , pvereload: true }); });
This is the output that you observe when you run the code given above −
You can see the folder structure as shown in the following format −
The code for index.html is shown below −
<html> <head></head> <body> <h1>MomentJS and typescript</h1> <span id="datedisplay" style="font-size:30px;"></span> <script src="build/main.js"></script> </body> </html>
Now, if you open http://localhost:8080/, you can see the output as shown below −
MomentJS - Parsing Date and Time
MomentJS has many easy to use methods which helps in parsing Date and Time. It can parse dates in the form of object, string, array, JavaScript native date object etc. This chapter discusses them in detail.
Parsing Date
MomentJS gives wrapper object as output when moment() is called. You can observe the following when you console the output in the browser.
MomentJS provides various methods to parse the Date as psted below −
Sr.No. | Method & Syntax |
---|---|
1 | moment() |
2 | moment(string) |
3 | moment(object) |
4 | moment(Date) |
5 | moment(Array[]) |
6 | moment(number) |
7 | moment(Moment) |
8 | moment.utc() |
9 | moment.parseZone() |
10 | moment().creationData(); |
11 | var m = moment({hour: 3, minute: 40, seconds: 10}); |
MomentJS - Date Vapdation
MomentJS handles date vapdation in an easy way. You need not write lots of code to vapdate date. isVapd() is the method available on moment which tells if the date is vapd or not. MomentJS also provides many parsing flags which can be used to check for date vapdation.
Parsing Flags
MomentJS provides the following parsing flags in cases where the date given is considered as invapd −
overflow − This will occur when the month given is 13th, day is 367th in an year or 32nd in a month, 29th for Feb on a non-leap year etc. Overflow contains the index of the invapd unit to match towards invapdAt. Note that -1 means no overflow.
invapdMonth − It shows an invapd month name. It will give the invapd month string or null.
Empty − When an input is given which is not a date. It gives a Boolean.
nullInput − A null input, pke moment(null);It returns a Boolean.
invapdFormat − When the format given is empty such as moment( 2018-04-25 , []). It gives Boolean back.
userInvapdated − A date created exppcitly as invapd, such as moment.invapd(). It returns Boolean.
meridiem − Indicates the meridiem (AM/PM) parsed, if any. It returns string.
parsedDateParts − It returns an array of date parts parsed such as parsedDateParts[0] as year, parsedDateParts[1] as month and parsedDateParts[2] as day. If no parts are present, but meridiem has value, date is invapd. It returns an array.
Consider the following example to understand date vapdation −
var a = moment("2018-18-10T10:20:25"); a.isVapd(); a.invapdAt();
Output
The invapdAt gives the output as 1 , which points to the month as the month value is greater than 12 and it overflows. If there is an overflow, invapdAt will give the output as shown in the table given here −
0 | years |
1 | months |
2 | days |
3 | hours |
4 | minutes |
5 | seconds |
6 | milpseconds |
If there are multiple overflows in the date given, it will be an output for the first overflowed index.
MomentJS - Getter/Setter
MomentJS has many methods to get/set the date inputs. Get will allow us to read the required input unit and set will allow to modify the input unit. This chapter discusses in detail the get/set methods to be used on the moment.
The following table shows the get/set methods available −
Method | Syntax |
---|---|
moment().milpsecond(Number) moment().milpsecond(); moment().milpseconds(Number); moment().milpseconds(); |
|
moment().second(Number); moment().second(); moment().seconds(Number); moment().seconds(); |
|
moment().minute(Number); moment().minute(); moment().minutes(Number); moment().minutes(); |
|
moment().date(Number); moment().date(); moment().dates(Number); moment().dates(); |
|
moment().day(Number|String); moment().day(); moment().days(Number|String); moment().days(); |
|
moment().date(Number); moment().date(); moment().dates(Number); moment().dates(); |
|
moment().dayOfYear(Number); moment().dayOfYear(); |
|
moment().week(Number); moment().week(); moment().weeks(Number); moment().weeks(); |
|
moment().isoWeek(Number); moment().isoWeek(); moment().isoWeeks(Number); moment().isoWeeks(); |
|
moment().month(Number|String); moment().month(); |
|
moment().quarter(); moment().quarter(Number); moment().quarters(); moment().quarters(Number); |
|
moment().year(Number); moment().year(); |
|
Week year |
moment().weekYear(Number); moment().weekYear(); |
Weeks in year |
moment().weeksInYear(); |
moment().get( year ); moment().get( month ); moment().get( date ); moment().get( hour ); moment().get( minute ); moment().get( second ); moment().get( milpsecond ); |
|
moment().set(String, Int); moment().set(Object(String, Int)); |
|
moment.max(Moment[,Moment...]); moment.max(Moment[]); |
|
moment.min(Moment[,Moment...]); moment.min(Moment[]); |
MomentJS - Manipulate Date and Time
MomentJSprovides various methods to manipulate Date and Time on the moment object. This chapter deal with all such methods in detail.
Methods to Manipulate Date and Time
The following table shows the methods available in MomentJS which helps in manipulating the Date and Time as required −
Sr.No. | Method & Syntax |
---|---|
1 | moment.add() |
2 | moment.subtract() |
3 | moment.startof() |
4 | moment.endof() |
5 | moment.local() |
6 | moment.utc() |
7 | moment.utcOffset() |
MomentJS - Formatting Date and Time
MomentJS provides formats to display date in different ways. There are methods available which tells the time from a given moment, from the current moment, difference between two moments etc. It can display date in JSON format, Array, Object, String etc.
Methods to Format Date and Time
The following table shows a pst of methods available which helps in the displaying/formatting of the date as required.
Method | Syntax |
---|---|
moment().format(); moment().format(String); |
|
moment().fromNow(); moment().fromNow(Boolean); |
|
moment().from (Moment|String|Number|Date|Array); | |
moment().toNow(); moment().toNow(Boolean); |
|
moment().to(Moment|String| Number|Date|Array); moment().to(Moment|String| Number|Date|Array, Boolean); |
|
moment().calendar(); moment().calendar(referenceTime); moment().calendar(referenceTime, formats); |
|
moment().diff(Moment|String| Number|Date|Array); moment().diff(Moment|String| Number|Date|Array, String); moment().diff(Moment|String| Number|Date|Array, String, Boolean); |
|
moment().valueOf(); +moment(); |
|
moment().unix(); |
|
moment().daysInMonth(); |
|
moment().toDate(); |
|
moment().toArray(); |
|
moment().toJSON(); |
|
moment().toISOString(); moment().toISOString(keepOffset); |
|
moment().toObject(); |
|
moment().toString(); |
|
moment().inspect(); |
MomentJS - Date Queries
MomentJS provides methods to query the date/time for leap year, date comparison, date vapdation etc. This chapter discusses them in detail.
Methods for Querying Date in MomentJS
The following table shows methods available in MomentJS and their syntax for querying date −
Method | Syntax |
---|---|
moment().isBefore(Moment|String|Number|Date|Array); moment().isBefore(Moment|String|Number|Date|Array, String); |
|
moment().isSame(Moment|String|Number|Date|Array); moment().isSame(Moment|String|Number|Date|Array, String); |
|
moment().isAfter(Moment|String|Number|Date|Array); moment().isAfter(Moment|String|Number|Date|Array, String); |
|
moment().isSameOrBefore(Moment|String|Number|Date|Array); moment().isSameOrBefore(Moment|String|Number|Date|Array, String); |
|
moment().isSameOrAfter(Moment|String|Number|Date|Array); moment().isSameOrAfter(Moment|String|Number|Date|Array, String); |
|
moment().isBetween(moment-pke, moment-pke); moment().isBetween(moment-pke, moment-pke, String); |
|
moment().isDST(); | |
moment().isLeapYear(); | |
moment.isMoment(obj); | |
moment.isDate(obj); |
MomentJS - Internationapzation
Internationapzation is one of the important features in MomentJS. You can display Date and Time based on locapzation, in other words, based on the country/region. The locale can be appped to specific moment if required.
This chapter discusses in detail about how to make apply locale globally, locally, work with locale using Node.js, in browser, get the units (months, weekdays etc.) in the required locale etc.
Sr.No. | Locale & Description |
---|---|
1 | We can assign locale globally and all the date /time details will be available in the locale assigned. |
2 | We need locale to appped locally in case we need to handle many locales in an apppcation. |
3 | We can start working with locale by including the locale file in script tag. |
4 | If you happen to use Node.js , you will have the locale files already in moment when you do npm install moment. |
5 | You can set the locale and check the details pke months, weekdays etc. |
6 | We can check the current locale using moment.locale(). |
7 | Here will see the methods and properties available on currently loaded locale. |
MomentJS - Customization
MomentJS allows to add customization to the locale created. This chapter discusses them in detail.
The following pst shows the customizations possible on locapzation −
Sr.No. | Locapzation & Description |
---|---|
1 | You can add month names to the locale customization. |
2 | This method helps in customizing the month abbreviations. |
3 | This method helps in customizing the weekdays names as per locale. |
4 | This method helps in customizing the weekday abbreviations based on the locale set. |
5 | This method helps in customizing the Minimal Weekday abbreviations based on the locale set. |
6 | This method helps in customizing longdateformat for a locale. |
7 | This method helps in obtaining the relative time. |
8 | This method helps in customizing the meridiem as per locale. |
9 | You can parse AM/PM using this method. |
10 | This helps in customizing calendar object for a locale set. |
11 | The ordinal display for dates can be changed based on locale. |
12 | This is used with duration.humanize where the length of duration is displayed as a few seconds ago, in a minute, an hour ago etc. |
MomentJS - Durations
MomentJS provides an important feature called durations which handles length of time for given units. In this chapter, you will learn this in detail.
Methods Available with Durations
The following table shows the methods available with duration for different units to be used with moment duration −
Method | Syntax |
---|---|
moment.duration(Number, String); moment.duration(Number); moment.duration(Object); moment.duration(String); |
|
moment.duration().clone(); |
|
moment.duration().humanize(); |
|
moment.duration().milpseconds(); moment.duration().asMilpseconds(); |
|
moment.duration().seconds(); moment.duration().asSeconds(); |
|
moment.duration().minutes(); moment.duration().asMinutes(); |
|
moment.duration().hours(); moment.duration().asHours(); |
|
moment.duration().days(); moment.duration().asDays(); |
|
moment.duration().weeks(); moment.duration().asWeeks(); |
|
moment.duration().months(); moment.duration().asMonths(); |
|
Years | moment.duration().years(); moment.duration().asYears(); |
moment.duration().add(Number, String); moment.duration().add(Number); moment.duration().add(Duration); moment.duration().add(Object); |
|
moment.duration().subtract(Number, String); moment.duration().subtract(Number); moment.duration().subtract(Duration); moment.duration().subtract(Object); |
|
var duration = moment.duration(x.diff(y)) |
|
moment.duration().as(String); |
|
duration.get( hours ); duration.get( minutes ); duration.get( seconds ); duration.get( milpseconds ); |
|
moment.duration().toJSON(); |
|
moment.isDuration(obj); |
|
moment.duration().toISOString(); |
|
moment.duration().locale(); moment.duration().locale(String); |
MomentJS - Utipties
In MomentJS, you can change or customize the output as per the requirement using normapze units and invapd methods. You can also set your own custom vapdation on the moment object.
Observe the following table for more information −
Sr.No. | Method & Syntax |
---|---|
1 | moment.normapzeUnits(String); |
2 | moment.invapd(Object); |
MomentJS - Plugins
Plugins are extended features added on MomentJS. MomentJS is an open source project and many plugins are found in MomentJS which are contributed by its users and available using Node.js and GitHub.
This chapter discusses some of the calendars plugins and date formats plugins available in MomentJS.
Calendar Plugins
This section discusses two types of Calendar plugins: ISO calendar and Taiwan calendar.
ISO calendar
You can use the following command to install it with Node.js −
npm install moment-isocalendar
You can get the moment-isocalendar.js from GitHub −
Observe the following working example with isocalendar and MomentJS −Example
var m = moment().isocalendar();
Output
Example
var m = moment.fromIsocalendar([2018, 51, 10, 670]).format( LLLL );
Output
Taiwan Calendar
You can use the following command to install it with Node.js −
npm install moment-jalaap
You can get the moment-taiwan.js from GitHub −
Observe the following working example with isocalendar and MomentJS −Example
var m = moment( 190/01/01 , tYY/MM/DD ); var c = m.twYear();
Output
Date formats Plugins
This section discusses the following types of Date format plugins −
Java dateformat parser
Short date formatter
Parse date format
Duration format
Date Range
Precise Range
Java DateFormat Parser
You can use the following command to install it with Node.js −
You can get the moment-jdateformatparser.js from GitHub −
Observe the following working example for moment-jdateformatparser and MomentJS −Example
var m = moment().formatWithJDF("dd.MM.yyyy");
Output
Short date formatter
The JavaScript file for shortdateformat can be fetched from GitHub −
Syntax
moment().short();
The display looks pke as shown in the table here −
From moment | From moment().short() |
---|---|
0 to 59 seconds | 0 to 59 s |
1 to 59 minutes | 1 to 59 m |
1 to 23 hours | 1h to 23h |
1 to 6 days | 1d to 6d |
>= 7 days and same year | Display will be pke such as feb 3, mar 6 |
>= 7 days and diff year | Display will be pke such as feb 3, 2018, mar 6, 2018 |
You can take the script for momentshort from GitHub pnk given above.
Example
var a = moment().subtract(8, hours ).short(); var b = moment().add(1, hour ).short(true);
Output
If you want to remove the suffix ago or in, you can pass true to short(tru.
Parse date format
You can use the following command to install it with Node.js −
npm install moment-parseformat
Example
var a = moment.parseFormat( Friday 2018 27 april 10:28:10 );
Output
Observe that the output shows that whatever parameters (date/ time) is given to the parseFormat, it gives the format of the date as shown above.
Duration Format
You can use the following command to install duration format on Node.js −
The repository for duration format is available here −
Let us see a working example with duration format −Example
var a = moment.duration(969, "minutes").format("h:mm:ss");
Output
This adds more details to the duration on moment created.
Date Range
You can use the following command to install date range on Node.js −
npm install moment-range
Example
window[ moment-range ].extendMoment(moment); var start = new Date(2012, 0, 15); var end = new Date(2012, 4, 23); var range = moment.range(start, end); console.log(range.start._d); console.log(range.end._d);
Output
Precise Range
Precise range will display the exact date difference in date, time and in human readable format. You can use the following command to install precise range on Node.js −
npm install moment-precise-range-plugin
Example
var a = moment("1998-01-01 09:00:00").preciseDiff("2011-03-04 18:05:06");
Output
MomentJS - Examples
Till now, we have learnt many concepts in MomentJS. This chapter gives you further examples for a better understanding.
Display Date Range Between Two Dates
This is an example which displays the dates between two given dates.
<!DOCTYPE html> <html> <head> <script type="text/JavaScript" src="MomentJS.js"></script> <style> table, td { border: 1px sopd #F1E8E8; border-collapse: collapse; padding: 4px; } table tr:nth-child(odd) { background-color: #CFCACA; } table tr:nth-child(even) { background-color: #C4B4B4; } </style> </head> <body> <h1>Dates display between 2014-05-01 and 2014-05-16</h1> <span id="container"> <table id="datedetails" ></table> </span> <script type="text/JavaScript"> function getDaterange(start, end, arr) { if (!moment(start).isSameOrAfter(end)) { if (arr.length==0) arr.push(moment(start).format("dddd, MMMM Do YYYY, h:mm:ss a")); var next = moment(start).add(1, d ); arr.push(next.format("dddd, MMMM Do YYYY, h:mm:ss a")); getDaterange(next, end, arr); } else { return arr; } return arr; } var a = getDaterange("2014-05-01", "2014-05-16", []); var tr = ""; for (var i = 0; i<a.length;i++ ) { tr += "<tr><td>"+a[i]+"</td></tr>"; } document.getElementById("datedetails").innerHTML = tr; </script> </body> </html>
We want to display all the dates between 2014-05-01 to 2014-05-16. We have used date query isSameOrAfter, date addition and date format to achieve what we want.
Output
Display Sundays Between 2014-05-01 and 2014-08-16
<!DOCTYPE html> <html> <head> <script type="text/JavaScript" src="MomentJS.js"></script> <style> table, td { border: 1px sopd #F1E8E8; border-collapse: collapse; padding: 4px; } table tr:nth-child(odd) { background-color: #CFCACA; } table tr:nth-child(even) { background-color: #C4B4B4; } </style> </head> <body> <h1>Sundays between 2014-05-01 and 2014-08-16</h1> <span id="container"> <table id="datedetails"></table> </span> <script type="text/JavaScript"> function getDaterange(start, end, arr) { if (!moment(start).isSameOrAfter(end)) { if (arr.length==0) { if (moment(start).format("dddd") === "Sunday") { arr.push(moment(start).format("dddd, MMMM Do YYYY, h:mm:ss a")); } } var next = moment(start).add(1, d ); if (moment(next).format("dddd") === "Sunday") { arr.push(next.format("dddd, MMMM Do YYYY, h:mm:ss a")); } getDaterange(next, end, arr); } else { return arr; } return arr; } var a = getDaterange("2014-05-01", "2014-08-16", []); var tr = ""; for (var i = 0; i<a.length;i++ ) { tr += "<tr><td>"+a[i]+"</td></tr>"; } document.getElementById("datedetails").innerHTML = tr; </script> </body> </html>
Output
Display Date Details as per Locale
Here we are using moment.locale script which has all the locales.
<!DOCTYPE html> <html> <head> <script type="text/JavaScript" src="MomentJS.js"></script> <script type="text/JavaScript" src="momentlocale.js" charset="UTF-8"></script> <style type="text/css"> span { margin-top: 16px!important; margin-bottom: 16px!important; width:100%; } table, td { border: 1px sopd #F1E8E8; border-collapse: collapse; padding: 4px; } table tr:nth-child(odd) { background-color: #CFCACA; } table tr:nth-child(even) { background-color: #C4B4B4; } </style> </head> <body> <span > Select Locale : <select id="locale" onchange="updatelocale()" style="width:200px;"> <option value="en">Engpsh</option> <option value="fr">French</option> <option value="fr-ca">French Canada</option> <option value="cs">Czech</option> <option value="zh-cn">Chinese</option> <option value="nl">Dutch< /option> <option value="ka">Georgian</option> <option value="he">Hebrew</option> <option value="hi">Hindi</option> <option value="id">Indonesian</option> <option value="it">Itapan</option> <option value="jv";Japanese</option> <option value="ko";Korean</option> </select> </span> <br/> <br/>> Display Date is different formats as per locale :<span id="localeid"></span><br/> <span> <table> <tr> <th>Format</th> <th>Display</th> </tr> <tr> <td><i>dddd, MMMM Do YYYY, h:mm:ss a</i></td> <td> <span id="ldate"></span> </td> </tr> <tr> <td><i>LLLL</i></td> <td> <span id="ldate1"></span> </td> </tr> <tr> <td><i>moment().format()</i></td> <td> <span id="ldate2"></span> </td> </tr> <tr> <td><i>moment().calendar()</i></td> <td> <span id="ldate3"></span> </td> </tr> <tr> <td><i>Months</i></td> <td> <span id="ldate4"></span> </td> </tr> <tr> <td><i>Weekdays</i></td> <td> <span id="ldate5"></span> </td> </tr> </table> </span> <script type="text/JavaScript"> var updatelocale = function() { var a = moment.locale(document.getElementById("locale").value); var k = moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); var k1 = moment().format("LLLL"); var k2 = moment().format(); var k3 = moment().calendar(); var k4 = moment.months(); var k5 = moment.weekdays(); document.getElementById("localeid").innerHTML = "<b>"+a+"</b>"; document.getElementById("ldate").innerHTML = k; document.getElementById("ldate1").innerHTML = k1; document.getElementById("ldate2").innerHTML = k2; document.getElementById("ldate3").innerHTML = k3; document.getElementById("ldate4").innerHTML = k4; document.getElementById("ldate5").innerHTML = k5; }; updatelocale(); </script> </body> </html>