browse by category or date

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!

GD Star Rating
loading...
How To Format Date In JavaScript Without External Library, 3.0 out of 5 based on 1 rating

Possibly relevant:

About Hardono

Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.

Incoming Search

javascript, jquery

No Comment

Add Your Comment