We all know that in the Java and PHP languages, there are classes and functions specifically used to format date objects, such as DateFormat in Java, and so on, and through these classes and functions, we can easily export a Date object to a string as required by the format, For example, for the same date December 25, 2006, the required display format might look like this:
December 25, 2010, 2010-12-25, 12-25-2010, et cetera.
In JavaScript, date objects are dates, so how do you output a Date object in a custom format?
The Date object has four built-in methods for outputting to a string format, respectively: Guangde County Energy Agency
- toGMTString, displays a date in GMT format
- toLocaleString, set a date as local operation
- toLocaleDateString, displays the date part of a Date object in local format
- toLocaleTimeString, displays the time portion of a Date object in local format
Although the JavaScript Date object has built-in methods to provide these output as strings, these strings are not in our control format, so what if we need our own custom special format?
Do not worry, Jsjava provides a dedicated class, specifically for the date of the specified format of the string output, you can download Jsjava-1.0.zip, the introduction of src/jsjava/text/dateformat.js, or directly introduced jslib/ Jsjava-1.0.js, the sample code is as follows:
var df=new dateformat (); Df.applypattern ("Yyyy-mm-dd hh:mm:ss"); var date=new date (2010,3,30,10,59,51); var str=df.format (date);
As you can see from the above example, what you need to do is to specify the pattern, so what does yyyy, MM, and so on mean in pattern? If you have studied the date formatting of Java, then you should know that it is all placeholders that have special functions, such as Y for year, and yyyy for four digits.
The effect shows the formatted date object as:
Date objects are: Fri Oct 21:40:01 gmt+0800 (China Standard Time)
JavaScript Code
<script type= "text/javascript" >date.prototype.format = function (format) {var o = {"m+": This.getmonth () +1,// Month "d+": This.getdate (), //day "H +": this.gethours (), //hour "m+": This.getminutes (),//minute "s+": This.getseconds (),//second "q+": Math.floor ((This.getmonth () +3)/3), //quarter "S": this.getmilliseconds ()// Millisecond}if (/(y+)/.test (format)) {Format=format.replace (regexp.$1, (this.getfullyear () + ""). substr (4-regexp.$ 1.length));} For (var k in O) {if (New RegExp ("(" + K + ")"). Test (format) {format = Format.replace (regexp.$1,regexp.$1.length==1? O[k]: ( "XX" + o[k]). substr (("" + o[k]). length);}} return format;} var d = new Date ();d ocument.write (' Date object: ');d ocument.write (d); var str = D.format (' yyyy-mm-dd '); var today = document.getElementById ("Todaybutton"); today.value = str;</script>
A JavaScript date formatting extension function