DateFormatter using moment

Run Settings
LanguageJavaScript
Language Version
Run Command
/** * @author: K. Lae Kettavong * * @date: 4/22/19 * * @description: Using node, moment, ES6, and IIFE to demonstrate polymorphism, * static static funtions and "private" variables * */ const moment = require("moment"); // using IIFE to encapsulate "private" members const DateFormatter = (() => { // date formats used in SLO-Service repo const format = { SPACE_MMMM_YYYY: "MMMM YYYY", // March 2019 COMMA_MMM_DD_YYYY: "MMM DD, YYYY", // Mar 18, 2019 COMMA_MMMM_DD_YYYY: "MMMM DD, YYYY", // March 18, 2019 COMMA_MMMM_DO_YYYY: "MMMM Do, YYYY", // March 18th, 2019 SLASH_MM_DD_YY: "MM/DD/YY", // 03/18/19 SLASH_MM_YYYY: "MM/YYYY", // 03/2019 SLASH_MM_DD_YYYY: "MM/DD/YYYY", // 03/18/2019 DASH_YYYY_MM: "YYYY-MM", // 2019-03 DASH_YYYY_MM_DD: "YYYY-MM-DD", // 2019-03-18 } const InvalidDateError = class extends Error { constructor(msg = "Invalid date") { super(msg); } } return class { /** * Returns date in full month and year format * @function getFullMonthYear * @param {string} date - date string to format * @return date in MMMM YYYY format - e.g. March 2019 */ static getFullMonthYear(date){ return this.getDate(date, format.SPACE_MMMM_YYYY); } /** * Returns date in numeric month and full year format * @function getShortMonthSlashFullYear * @param {string} date - date string to format * @return date in MM/YYYY format - e.g. 03/2019 */ static getShortMonthSlashFullYear(date){ return this.getDate(date, format.SLASH_MM_YYYY); } // returns "private" constants static get format(){ return format; } /** * Returns date in the specified format * @function getDate * @param {string} date - date string to format * @param {string} format - date format * @return date in specified format */ static getDate(date, format){ this.validate(date, format); return moment(date).format(format); } /** * Verifies if date in the specified format is valid * @function validate * @param {string} date - date string to format * @param {string} format - date format * @throws throws InvalidDateError if date and format don't match up */ static validate(date, format) { if(!moment(date, format, true).isValid()) { this.throwInvalidDateError(); } } /** * Throws InvalidDateError * @function throwInvalidDateError * @throws throws InvalidDateError */ static throwInvalidDateError(){ throw new InvalidDateError(); } } })(); const date = new Date(); console.log(DateFormatter.getFullMonthYear(date)); // March 2019 console.log(DateFormatter.getShortMonthSlashFullYear(date)); // 03/2019 console.log(DateFormatter.getDate(date, DateFormatter.format.DASH_YYYY_MM_DD)); // 2019-03-18
Editor Settings
Theme
Key bindings
Full width
Lines