MomentJS is a JavaScript library which helps is parsing, validating, 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 localization 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, validate date, get the maximum, minimum date etc. It is an open source project and you can easily contribute to the library and add features in the form of plugins and make it available on GitHub and in Node.js.
Let us understand in detail all the important features available with MomentJS −
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 Validation is very easy with MomentJS. You can use the method isValid() and check whether the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.
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 allows to read and set the units in the date. It allows to change as well as read hour , minute, seconds, millisecond, 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 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 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 validation.
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.
Internationalization is yet another important features in MomentJS. You can display Date and Time based on locale. The locale can be applied 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 dealing 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.
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.
Utilities comes with two methods: normalize units and invalid. 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 validation on the moment object.
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.
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 library. You can access its files in any of the following methods −
In this method, we are going to need MomentJS file from its official website and will use it directly in the browser.
As a first step, go to the official website of MomentJS https://momentjs.comYou 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.
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 −
<html> <head> <title>MomentJS - Working Example</title> <script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script> <style> div { border: solid 1px #ccc; padding:10px; font-family: "Segoe UI",Arial,sans-serif; width: 50%; } </style> </head> <body> <div style = "font-size:25px" id = "todaysdate"></div> <script type = "text/JavaScript"> var a = moment().toString(); document.getElementById("todaysdate").innerHTML = a; </script> </body> </html>
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> <div id = "datedisplay" style = "font-size:30px;"></div> <script type = "text/JavaScript"> var a = moment.locale("fr"); var c = moment().format("LLLL"); document.getElementById("datedisplay").innerHTML = c; </script> </body> </html>
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().
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 −
In this chapter, we will discuss how to work with MomentJS using RequireJS and MomentJS and TypeScript.
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 − https://requirejs.org/docs/download.html. Observe the following code for a better understanding −
<!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> <div id="datedisplay" style="font-size:25px;"></div> </body> </html>
require.config({ paths:{ 'momentlocale':'libs/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 libs.
The following is the output for project.html that you will observe in the browser −
The code used for building MomentJS and Typescript project are as given below −
{ "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": "", "license": "ISC" }
Note that the dependencies available in package,json needs to be installed using npm install.
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.
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', livereload: 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> <div id="datedisplay" style="font-size:30px;"></div> <script src="build/main.js"></script> </body> </html>
Now, if you open http://localhost:8080/, you can see the output as shown below −
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.
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 listed below −
Sr.No. | Method & Syntax |
---|---|
1 | Now
moment() |
2 | String
moment(string) |
3 | Object
moment(object) |
4 | Date
moment(Date) |
5 | Array
moment(Array[]) |
6 | Unix Timestamp
moment(number) |
7 | Moment Clone
moment(Moment) |
8 | UTC
moment.utc() |
9 | parseZone
moment.parseZone() |
10 | Creation Data
moment().creationData(); |
11 | Defaults
var m = moment({hour: 3, minute: 40, seconds: 10}); |
MomentJS handles date validation in an easy way. You need not write lots of code to validate date. isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.
MomentJS provides the following parsing flags in cases where the date given is considered as invalid −
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 invalid unit to match towards invalidAt. Note that -1 means no overflow.
invalidMonth − It shows an invalid month name. It will give the invalid month string or null.
Empty − When an input is given which is not a date. It gives a Boolean.
nullInput − A null input, like moment(null);It returns a Boolean.
invalidFormat − When the format given is empty such as moment('2018-04-25', []). It gives Boolean back.
userInvalidated − A date created explicitly as invalid, such as moment.invalid(). 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 invalid. It returns an array.
Consider the following example to understand date validation −
var a = moment("2018-18-10T10:20:25"); a.isValid(); a.invalidAt();
The invalidAt 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, invalidAt will give the output as shown in the table given here −
0 | years |
1 | months |
2 | days |
3 | hours |
4 | minutes |
5 | seconds |
6 | milliseconds |
If there are multiple overflows in the date given, it will be an output for the first overflowed index.
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 |
---|---|
Millisecond |
moment().millisecond(Number) moment().millisecond(); moment().milliseconds(Number); moment().milliseconds(); |
Second |
moment().second(Number); moment().second(); moment().seconds(Number); moment().seconds(); |
Minute |
moment().minute(Number); moment().minute(); moment().minutes(Number); moment().minutes(); |
Hour |
moment().date(Number); moment().date(); moment().dates(Number); moment().dates(); |
Day of week |
moment().day(Number|String); moment().day(); moment().days(Number|String); moment().days(); |
Date of Month |
moment().date(Number); moment().date(); moment().dates(Number); moment().dates(); |
Day of year |
moment().dayOfYear(Number); moment().dayOfYear(); |
Week of year |
moment().week(Number); moment().week(); moment().weeks(Number); moment().weeks(); |
Week of year (ISO) |
moment().isoWeek(Number); moment().isoWeek(); moment().isoWeeks(Number); moment().isoWeeks(); |
Month |
moment().month(Number|String); moment().month(); |
Quarter |
moment().quarter(); moment().quarter(Number); moment().quarters(); moment().quarters(Number); |
Year |
moment().year(Number); moment().year(); |
Week year |
moment().weekYear(Number); moment().weekYear(); |
Weeks in year |
moment().weeksInYear(); |
Get |
moment().get('year'); moment().get('month'); moment().get('date'); moment().get('hour'); moment().get('minute'); moment().get('second'); moment().get('millisecond'); |
Set |
moment().set(String, Int); moment().set(Object(String, Int)); |
Maximum |
moment.max(Moment[,Moment...]); moment.max(Moment[]); |
Minimum |
moment.min(Moment[,Moment...]); moment.min(Moment[]); |
MomentJSprovides various methods to manipulate Date and Time on the moment object. This chapter deal with all such methods in detail.
The following table shows the methods available in MomentJS which helps in manipulating the Date and Time as required −
Sr.No. | Method & Syntax |
---|---|
1 | Add
moment.add() |
2 | Subtract
moment.subtract() |
3 | Start of Time
moment.startof() |
4 | End of Time
moment.endof() |
5 | Local
moment.local() |
6 | UTC
moment.utc() |
7 | UTC offset
moment.utcOffset() |
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.
The following table shows a list of methods available which helps in the displaying/formatting of the date as required.
Method | Syntax |
---|---|
Format |
moment().format(); moment().format(String); |
Time from now |
moment().fromNow(); moment().fromNow(Boolean); |
Time from X |
moment().from (Moment|String|Number|Date|Array); |
Time to now |
moment().toNow(); moment().toNow(Boolean); |
Time to X |
moment().to(Moment|String| Number|Date|Array); moment().to(Moment|String| Number|Date|Array, Boolean); |
Calendar Time |
moment().calendar(); moment().calendar(referenceTime); moment().calendar(referenceTime, formats); |
Difference |
moment().diff(Moment|String| Number|Date|Array); moment().diff(Moment|String| Number|Date|Array, String); moment().diff(Moment|String| Number|Date|Array, String, Boolean); |
Unix Timestamp(milliseconds) |
moment().valueOf(); +moment(); |
Unix Timestamp(seconds) |
moment().unix(); |
Days in Month |
moment().daysInMonth(); |
As JavaScript Date |
moment().toDate(); |
As Array |
moment().toArray(); |
As JSON |
moment().toJSON(); |
As ISO 8601 String |
moment().toISOString(); moment().toISOString(keepOffset); |
As Object |
moment().toObject(); |
As String |
moment().toString(); |
Inspect |
moment().inspect(); |
MomentJS provides methods to query the date/time for leap year, date comparison, date validation etc. This chapter discusses them in detail.
The following table shows methods available in MomentJS and their syntax for querying date −
Method | Syntax |
---|---|
Is Before |
moment().isBefore(Moment|String|Number|Date|Array); moment().isBefore(Moment|String|Number|Date|Array, String); |
Is Same |
moment().isSame(Moment|String|Number|Date|Array); moment().isSame(Moment|String|Number|Date|Array, String); |
Is After |
moment().isAfter(Moment|String|Number|Date|Array); moment().isAfter(Moment|String|Number|Date|Array, String); |
Is Same or Before |
moment().isSameOrBefore(Moment|String|Number|Date|Array); moment().isSameOrBefore(Moment|String|Number|Date|Array, String); |
Is Same or After |
moment().isSameOrAfter(Moment|String|Number|Date|Array); moment().isSameOrAfter(Moment|String|Number|Date|Array, String); |
Is Between |
moment().isBetween(moment-like, moment-like); moment().isBetween(moment-like, moment-like, String); |
Is Daylight Saving Time |
moment().isDST(); |
Is Leap Year |
moment().isLeapYear(); |
Is a Moment |
moment.isMoment(obj); |
Is a Date |
moment.isDate(obj); |
Internationalization is one of the important features in MomentJS. You can display Date and Time based on localization, in other words, based on the country/region. The locale can be applied 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 | Global locale
We can assign locale globally and all the date /time details will be available in the locale assigned. |
2 | Changing Locale Locally
We need locale to applied locally in case we need to handle many locales in an application. |
3 | Using Locale in Browser
We can start working with locale by including the locale file in script tag. |
4 | Using Locale using Node.js
If you happen to use Node.js , you will have the locale files already in moment when you do npm install moment. |
5 | momentjs_Listing date/time details of current locale
You can set the locale and check the details like months, weekdays etc. |
6 | Checking current locale
We can check the current locale using moment.locale(). |
7 | Accessing Locale Specific Functionality
Here will see the methods and properties available on currently loaded locale. |
MomentJS allows to add customization to the locale created. This chapter discusses them in detail.
The following list shows the customizations possible on localization −
Sr.No. | Localization & Description |
---|---|
1 | Month Names
You can add month names to the locale customization. |
2 | Month Abbreviation
This method helps in customizing the month abbreviations. |
3 | Weekday Names
This method helps in customizing the weekdays names as per locale. |
4 | Weekday Abbreviation
This method helps in customizing the weekday abbreviations based on the locale set. |
5 | Minimal Weekday Abbreviation
This method helps in customizing the Minimal Weekday abbreviations based on the locale set. |
6 | Long Date Formats
This method helps in customizing longdateformat for a locale. |
7 | Relative Time
This method helps in obtaining the relative time. |
8 | AM/PM
This method helps in customizing the meridiem as per locale. |
9 | AM/PM Parsing
You can parse AM/PM using this method. |
10 | Calendar
This helps in customizing calendar object for a locale set. |
11 | Ordinal
The ordinal display for dates can be changed based on locale. |
12 | Relative Time Thresholds
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 provides an important feature called durations which handles length of time for given units. In this chapter, you will learn this in detail.
The following table shows the methods available with duration for different units to be used with moment duration −
Method | Syntax |
---|---|
Creating |
moment.duration(Number, String); moment.duration(Number); moment.duration(Object); moment.duration(String); |
Clone |
moment.duration().clone(); |
Humanize |
moment.duration().humanize(); |
Milliseconds |
moment.duration().milliseconds(); moment.duration().asMilliseconds(); |
Seconds |
moment.duration().seconds(); moment.duration().asSeconds(); |
Minutes |
moment.duration().minutes(); moment.duration().asMinutes(); |
Hours |
moment.duration().hours(); moment.duration().asHours(); |
Days |
moment.duration().days(); moment.duration().asDays(); |
Weeks |
moment.duration().weeks(); moment.duration().asWeeks(); |
Months |
moment.duration().months(); moment.duration().asMonths(); |
Years | moment.duration().years(); moment.duration().asYears(); |
Add Time |
moment.duration().add(Number, String); moment.duration().add(Number); moment.duration().add(Duration); moment.duration().add(Object); |
Subtract Time |
moment.duration().subtract(Number, String); moment.duration().subtract(Number); moment.duration().subtract(Duration); moment.duration().subtract(Object); |
Using Duration with Diff |
var duration = moment.duration(x.diff(y)) |
As Unit of Time |
moment.duration().as(String); |
Get Unit of Time |
duration.get('hours'); duration.get('minutes'); duration.get('seconds'); duration.get('milliseconds'); |
As JSON |
moment.duration().toJSON(); |
Is a Duration |
moment.isDuration(obj); |
As ISO 8601 String |
moment.duration().toISOString(); |
Locale |
moment.duration().locale(); moment.duration().locale(String); |
In MomentJS, you can change or customize the output as per the requirement using normalize units and invalid methods. You can also set your own custom validation on the moment object.
Observe the following table for more information −
Sr.No. | Method & Syntax |
---|---|
1 | Normalize Units
moment.normalizeUnits(String); |
2 | Invalid
moment.invalid(Object); |
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.
This section discusses two types of Calendar plugins: ISO calendar and Taiwan 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 − https://github.com/fusionbox/moment-isocalendar 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
You can use the following command to install it with Node.js −
npm install moment-jalaali
You can get the moment-taiwan.js from GitHub − https://github.com/bradwoo8621/moment-taiwan Observe the following working example with isocalendar and MomentJS −
Example
var m = moment('190/01/01', 'tYY/MM/DD'); var c = m.twYear();
Output
This section discusses the following types of Date format plugins −
You can use the following command to install it with Node.js −
You can get the moment-jdateformatparser.js from GitHub − https://github.com/MadMG/moment-jdateformatparser Observe the following working example for moment-jdateformatparser and MomentJS −
Example
var m = moment().formatWithJDF("dd.MM.yyyy");
Output
The JavaScript file for shortdateformat can be fetched from GitHub −
https://github.com/researchgate/moment-shortformatSyntax
moment().short();
The display looks like 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 like such as feb 3, mar 6 |
>= 7 days and diff year | Display will be like such as feb 3, 2018, mar 6, 2018 |
You can take the script for momentshort from GitHub link 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.
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.
You can use the following command to install duration format on Node.js −
The repository for duration format is available here − https://github.com/jsmreese/moment-duration-format 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.
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 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
Till now, we have learnt many concepts in MomentJS. This chapter gives you further examples for a better understanding.
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 solid #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> <div id="container"> <table id="datedetails" ></table> </div> <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.
<!DOCTYPE html> <html> <head> <script type="text/JavaScript" src="MomentJS.js"></script> <style> table, td { border: 1px solid #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> <div id="container"> <table id="datedetails"></table> </div> <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>
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"> div { margin-top: 16px!important; margin-bottom: 16px!important; width:100%; } table, td { border: 1px solid #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> <div > Select Locale : <select id="locale" onchange="updatelocale()" style="width:200px;"> <option value="en">English</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">Italian</option> <option value="jv";Japanese</option> <option value="ko";Korean</option> </select> </div> <br/> <br/>> Display Date is different formats as per locale :<span id="localeid"></span><br/> <div> <table> <tr> <th>Format</th> <th>Display</th> </tr> <tr> <td><i>dddd, MMMM Do YYYY, h:mm:ss a</i></td> <td> <div id="ldate"></div> </td> </tr> <tr> <td><i>LLLL</i></td> <td> <div id="ldate1"></div> </td> </tr> <tr> <td><i>moment().format()</i></td> <td> <div id="ldate2"></div> </td> </tr> <tr> <td><i>moment().calendar()</i></td> <td> <div id="ldate3"></div> </td> </tr> <tr> <td><i>Months</i></td> <td> <div id="ldate4"></div> </td> </tr> <tr> <td><i>Weekdays</i></td> <td> <div id="ldate5"></div> </td> </tr> </table> </div> <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>