var UtilDate={
formateDate:function(date,str){
if(str.indexOf('yyyy')>=0){
str=str.replace('yyyy',date.getFullYear());
}
if(str.indexOf('MM')>=0){
str=str.replace('MM',date.getMonth()+1);
}
if(str.indexOf('dd')>=0){
str=str.replace('dd',date.getDate());
}
if(str.indexOf('HH')>=0){
str=str.replace('HH',date.getHours());
}
if(str.indexOf('mm')>=0){
str=str.replace('mm',date.getMinutes());
}
if(str.indexOf('ss')>=0){
str=str.replace('ss',date.getSeconds());
}
return str;
}
}
调用方法:
var date=new Date();
UtilDate.formateDate(date,'yyyy-MM-dd');
希望对你有帮助
本文介绍了一种使用JavaScript进行日期格式化的实用方法,通过自定义字符串模板,可以轻松地将日期转换为各种常见格式,如'yyyy-MM-dd'。这种方法灵活且易于实现,适用于多种应用场景。

2万+

被折叠的 条评论
为什么被折叠?



