JavaScript

JavaScript Date Formatting: Practical Display Guide Using dateformat.js

When using JavaScript, displaying dates in a specific format is a common requirement. While many programming languages, such as PHP and Perl, have built-in functions or methods to format dates, JavaScript’s standard features do not offer such convenient functionality. However, this issue can be resolved by using external libraries. This time, we’ll take a detailed look at how to display dates in a specified format using dateformat.js.

Introducing the dateformat.js Library

First, you need to introduce dateformat.js to your project. Add the following tag to an appropriate place in your HTML to load the library.

<script type="text/javascript" src="dateformat.js"></script>

HTML for Displaying Formatted Dates

Next, create an HTML element to display the formatted date results. The following code has text areas for displaying dates in two different formats.

<div id="idDate">
    yyyy/MM/dd HH:mm:ss SSS
	<input typy="text" id="idyyyymmddhhmmsssss" value="yyyymmddhhmmsssss" size="30">

    yyyyMMdd
	<input typy="text" id="idYYMMDD" value="YYMMDD" size="30">
</div>

Formatting Dates with dateformat.js

Next, write the JavaScript code to actually format the dates. This code will use two different formats to get the current date and time, and display the results in the text areas created above.

<script type="text/javascript">
	// Format pattern 01
	var dateFormat01 = new DateFormat("yyyy/MM/dd HH:mm:ss SSS");
	// Format pattern 02
	var dateFormat02 = new DateFormat("yyyyMMdd");
	
	// Get current date and time
	var stryyyymmddhhmmsssss = dateFormat01.format(new Date());
	var strYYMMDD = dateFormat02.format(new Date());
	
	// Output the formatted date and time
	document.getElementById("idyyyymmddhhmmsssss").value = stryyyymmddhhmmsssss;
	document.getElementById("idYYMMDD").value = strYYMMDD;
</script>

dateformat.js: Demo Page for Displaying Date and Time in a Specified Format

If you want to check the specific operation and results, refer to the demo page below.

dateformat.js: Demo Page for Displaying Date and Time in a Specified Format

Source: dateformat.js – Date Format Conversion Library

dateformat.js is a very useful library, but you can access the original information and detailed documentation from the link below.

Source:dateformat.js – Date Format Conversion Library

Finally

Quite a long time ago, before jQuery came along, many developers struggled with date formatting. However, with the advent of libraries like dateformat.js, this issue has been easily resolved. By referring to the steps above, you can effectively display date formatting in JavaScript.

 
※ Please use it at your own risk if you reuse it.
 Do not reuse the Google Analytics tags within the demo page tag.