This article is mainly on the JavaScript Date object format into a string implementation of the method is introduced in detail, the need for friends can come to the reference, I hope to help you.
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 . principles like YYYYMMDD: 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 . Implementation of a total of two functions, paste can be run . expansion: Example only supports the time of the month and the second millisecond of the element, if you need to display the week you can add W = getday () in values, To modify a regular expression to y+| m+|d+| h+|m+|s+| s+|w+| [^ymdhmssw]/g can . If you need to display the month or week as a full or simple spelling, add the appropriate configuration to the CFG, I only added an example to the CFG How to use: var Date = new Date (); var str = formatdate (date, ' yyyy mmm month dd Day '); the value of STR is July 29, 2012 code as follows:/**& nbsp * Format integers * @param number:number integers to be formatted * @param fmt:string integer format */ function FormatNumber (number, F MT) { Number = number + '; if (Fmt.length > Number.length) { return fmt.substring (number.length) + N umber; } return number; } /** * format date is a string representation * @param datetime:date the Date object to format &NB Sp * @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.gethour S (), m:datetime.getminutes (), s:datetime.getseconds (), s:datetime.getmilliseconds () };& nbsp /* Split the date format with a regular expression */ var elems = Format.match (/y+| m+|d+| h+|m+|s+| s+| [^ymdhmss]/g); //Replace the date element with the actual value for (var i = 0; i < elems.length; i++) { if (Cfg[elems[i]) { ele Ms[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 ('); }