The date formatting provided by JavaScript is too simple. Generally, the application needs to implement the formatting method by myself. Below is a formatting process that I want to get out. It should be able to meet the common needs. Use text as a separatist, and even supports formatting without separators like yyyymmdd.
Principles: Use the regular expression to divide the date elements in the date template [such as yyyyy, mm, DD], and separators, and then use the actual value to replace the date element to form the date string.
A total of two functions are implemented, and the paste can be run.
Extension method:
In the example, only the element of milliseconds in the year, month, and day. If you need to display the week, you can add w = getDay () to the value of the value, and modify the regular expression to y+| m+| d+| h+| s+| s+| w+| [^ymdhmsSW]/g.
If you need to display the month or week as full or simple, you can add the corresponding configuration to the CFG. I only add an example to the CFG
How to use:
var date = new date ();
var Str = Formatdate (Date, 'Yyyy Year MMM Month DD Day');
The value of STR is July 29, 2012
Copy code code as follows:
/**
* Formatal integer
* @param Number: Number to format the integer
* @param FMT: String integer format
*/
Function Formatnumber (Number, FMT) {
number = number + '';
if (fmt.length> number.Length) {
Return FMT.Substring (Number.Length) + Number;
}
Return number;
}
/**
* The formatting date is the string representation
* @param datetime: Date to formatting the date object
* @param Format: String Date Format
*/
Function Formatdate (DateTime, Format) {{
var cfg = {
Mmm: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'ten two'],
Mmmm: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'ten two']
},
Values = {{
y: dough.getfullyear (),
M: dough.getmonth (),
D: datetime.getdate (),
H: dates.getHours (),
m: dough.getminutes (),
s: dough.getSeconds (),
S: dough.getmilliseConds ()
};
/*Use a regular expression to split the date format of each element*/
var elems = format.match (/y+| m+| d+| h+| m+| s+| s+| [^ymdhmsS]/g);
// Replace the date element to the actual value
for (var I = 0; I <elems.length; i ++) {
if (cfg [elems [i]]) {
elems [i] = cfg [elems [i]] [Values [Elems [i] .charat (0)];;
} Else if (values [elems [i] .charat (0)]) {) {
Elems [i] = Formatnumber (Values [Elems [i] .charat (0)], Elems [i] .RePlace (/./ G, '0'));
}
}
Return Elems.join ('');
}