MomentJS – Useful Resources ”; Previous Next The following resources contain additional information on MomentJS. Please use them to get more in-depth knowledge on this. Python Programming Certification 2024 Most Popular 9 Courses 1 eBooks Tutorialspoint More Detail Artificial Intelligence and Machine Learning Certification 2024 Most Popular 7 Courses 1 eBooks Tutorialspoint More Detail Java Certification 2024 Best Seller 7 Courses 1 eBooks Tutorialspoint More Detail Print Page Previous Next Advertisements ”;
Category: momentjs
MomentJS – Overview
MomentJS – Overview ”; Previous Next 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. 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 Validation 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. 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, 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 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 validation. 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. Internationalization 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. 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. Utilities 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 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. Print Page Previous Next Advertisements ”;
MomentJS – Introduction
MomentJS – Introduction ”; Previous Next 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 − https://requirejs.org/docs/download.html. 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> <div id=”datedisplay” style=”font-size:25px;”></div> </body> </html> main.js 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 − 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”: “”, “license”: “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”, 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 − Print Page Previous Next Advertisements ”;
MomentJS – Durations
MomentJS – Durations ”; Previous Next 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 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); Print Page Previous Next Advertisements ”;
MomentJS – Environment Setup
MomentJS – Environment Setup ”; Previous Next 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 − 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 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. 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 Live Demo <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> 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 − Live Demo <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> 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 − Print Page Previous Next Advertisements ”;
MomentJS – Examples
MomentJS – Examples ”; Previous Next 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 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. 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 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> 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”> 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> Output 1 Output 2 Output 3 Output 4 Print Page Previous Next Advertisements ”;
MomentJS – Home
MomentJS Tutorial PDF Version Quick Guide Resources Job Search Discussion MomentJS is a JavaScript library which helps is parsing, validating, manipulating and displaying date and time in JavaScript in a very easy way. MomentJS can be used directly inside a browser and also with Node.js. Working with dates and time using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with dates. MomentJS comes with lots of features that eases your work with date and time. Audience This tutorial is designed for software programmers who want to learn the basics of MomentJS and its programming concepts in simple and easy way. This tutorial will give you enough understanding on various functionalities of MomentJS with suitable examples. Prerequisites This tutorial is designed keeping in mind that its readers have a basic understanding of HTML, CSS, and JavaScript. If you are new to these concepts, we recommend you to go through relevant tutorials and gain an understanding on them, before you proceed with this tutorial. Print Page Previous Next Advertisements ”;
MomentJS – Discussion
Discuss MomentJS ”; Previous Next MomentJS is a JavaScript library which helps is parsing, validating, manipulating and displaying Date and Time in JavaScript in a very easy way. MomentJS can be used directly inside a browser and also with Node.js. Working with dates and time using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with dates. MomentJS comes with lots of features that eases your work with Date and Time. Print Page Previous Next Advertisements ”;
MomentJS – Date Queries
MomentJS – Date Queries ”; Previous Next MomentJS provides methods to query the date/time for leap year, date comparison, date validation 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 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); Print Page Previous Next Advertisements ”;
MomentJS – Date Validation
MomentJS – Date Validation ”; Previous Next 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. Parsing Flags 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(); Output 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. Print Page Previous Next Advertisements ”;