For most of us, Date formatting in JavaScript is handled by external library/plugin (jQuery’s dateFormat, jQuery-UI’s datepicker). But if somehow your project has no access to them, you can extend Date by yourself.
window.Date.prototype.format = function(fmt){ if (!fmt) return this.toString(); var rgx = /[a-zA-Z]+/g; if (fmt.replaceAll) { var year = this.getFullYear().toString(); var month = this.getMonth(); var date = this.getDate(); var arMonths = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; var that = this; fmt = fmt.replaceAll(rgx, function (f) { switch (f) { case "yyyy": return year; case "yy": return year.substr(2); case "MMM": return arMonths[month]; case "dd": return date.toString().padStart(2, "0"); } return f; }); } return fmt; }
Now you can the new format function in the Date class
As shown above, if format function is unable to handle the format string specified, it will just returns the original text. What you need to do now is to add the new case inside switch(f){ …. }. For example, we want to handle HH format.
switch (f) { // ... SNIP ... case "HH": return that.getHours().toString().padStart(2, "0"); }
Now, we should see the correct value.
I hope it helps. Cheers!