Home >Web Front-end >JS Tutorial >Implementation method of formatting javascript date object into string_javascript skills
The date formatting provided by JavaScript is too simple. Generally, applications need to implement the formatting method by themselves. Below is a formatting solution I came up with, which should be able to meet common needs. Any separator can be used in the date template. , you can also use text as a separator, and even support formatting without separators like yyyyMMdd.
Principle: Use regular expressions to convert the date elements in the date template [such as yyyy , MM, dd] and delimiters into an array, and then replace the date elements with the actual values to form a date string.
There are two functions in the implementation, which can be run by pasting.
Extension method:
The example only supports elements of year, month, day, hour, minute, second and millisecond. If you need to display the day of the week, you can add w = getDay() in values and modify the regular expression to y |M |d |H |m |s |S |w |[^yMdHmsSw]/g is enough.
If you need to display the month or week in full or simplified English, you can add the corresponding configuration in cfg. I only added an example in cfg
Usage:
var date = new Date();
var str = formatDate(date, 'yyyy year MMM month dd day');
Then the value of str is July 29, 2012
/**
* Format date as string representation
* @param datetime:Date The date object to be formatted
* @param format:String Date format
*/
function formatDate(datetime, format) {
var cfg = {
MMM : ['一', '二', '三', '四' , 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'],
MMMM : ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
},
values = {
y : datetime.getFullYear(),
M : datetime.getMonth(),
d : datetime.getDate(),
H : datetime.getHours(),
m : datetime.getMinutes(),
s : datetime.getSeconds(),
S : datetime.getMilliseconds()
};
/*Use regular expressions to split each element of the date format* /
var elems = format.match(/y |M |d |H |m |s |S |[^yMdHmsS]/g);
//Replace date elements with actual values
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('');
}