JavaScript中对日期格式化的新想法.

时间:2020-12-09 12:42:23

其实我们对与日期的显示,也就那么几种,不需要每次都传格式化字符串.

只要告诉函数你想要什么结果就好了,以下是在ios的JavaScript中我新写的日期格式化函数:

 /**
格式化日期
@param {String} formatStr-格式化字符串
@description
"date":显示日期.如:2017/09/09
"time":显示时间.如:15:09:05
"minute":显示到分钟.如:2017/09/09 15:09
"second"显示到秒.如:2017/09/09 15:09:05
@return {String} 格式化后的日期
*/
Date.prototype.format = function(formStr) {
var date = this;
var year,month,day,hour,minute,second;
var dateStr,minuteStr,secondStr; year=date.getFullYear(); month=date.getMonth()+1; day=date.getDate(); dateStr=year+"/"+(month<10?"0"+month:month)+"/"+(day<10?"0"+day:day);
if(formStr=="date") return dateStr; hour=date.getHours(); minute=date.getMinutes(); second=date.getSeconds(); minuteStr=(hour<10?"0"+hour:hour)+":"+(minute<10?"0"+minute:minute);
secondStr=minuteStr+":"+(second<10?"0"+second:second);
if(formStr=="time") return secondStr; if(formStr=="minute") return dateStr+" "+minuteStr; if(formStr=="second") return dateStr+" "+secondStr;
};

很low很实在.