JavaScript provides the date format is too simple, the general application needs to implement the format of the method. Here is a format I came up with, should be able to meet the common needs. You can use any separator in a date template, and you can use text as a separator. It even supports formatting without delimiters such as YYYYMMDD.
principle: use regular expressions to split date elements [such as YYYY, MM, DD] and delimiters in a date template into an array, and then replace the date element with the actual value to form a date string.
There are two functions to be implemented, paste to run.
Expansion mode:
In the example, only the elements that are seconds and milliseconds are supported, and if you need to display the week, you can add W = getday () in values to modify the regular expression to y+| m+|d+| h+|m+|s+| s+|w+| [^ymdhmssw]/g can be.
If you need to display the month or week as a full or simple spell, you can add a configuration to the CFG, and 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:
/**
* Format integers
* @param number:number The integer to be formatted
* @param fmt:string integer format
*/
function FormatNumber (number, FMT) {
Number = number + ';
if (Fmt.length > Number.length) {
Return fmt.substring (number.length) + number;
}
return number;
}
/**
* Format Date is string representation
* @param datetime:date The Date object to be formatted
* @param format:string Date format
*/
function FormatDate (datetime, format) {
var cfg = {
MMM: [' One ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine ', ' ten ', ' 11 ', ' 12 '],
MMMM: [' One ', ' two ', ' three ', ' four ', ' five ', ' six ', ' seven ', ' eight ', ' nine ', ' ten ', ' 11 ', ' 12 ']
},
Values = {
Y:datetime.getfullyear (),
M:datetime.getmonth (),
D:datetime.getdate (),
H:datetime.gethours (),
M:datetime.getminutes (),
S:datetime.getseconds (),
S:datetime.getmilliseconds ()
};
/* Split the date format elements with a regular expression * *
var elems = Format.match (/y+| m+|d+| h+|m+|s+| s+| [^ymdhmss]/g);
To replace a date element with an 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 (");
}