1 当给定时间为1997-10-10时转化为毫秒值,需要先提取这样的参数,在使用getTime
2 当给定的值为毫秒值 转化为日期显示时
function formatBeginTime(time){
var year = time.getFullYear();
var mouth = time.getMonth();//比实际只小,此处若加1下面新建时间将对应不上
var day = time.getDate();
var temp = new Date(year,mouth,day,00,00,00);
return temp;
}
3 带指定格式的日期显示:使用formatDate(date,‘yyyy-MM-dd hh:mm:ss’)
function formatDate (date, fmt) { if(!date){ return ''; } if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } let o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() } for (let k in o) { if (new RegExp(`(${k})`).test(fmt)) { let str = o[k] + '' fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str)) } } return fmt } function padLeftZero (str) { return ('00' + str).substr(str.length) }
4 格式化时间,当小于一天时小时小时及分钟,大于时显示日期
function convertTime(tem){ var curDate = new Date(); var numEng = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty','twenty-one','twenty-two','twenty-three','twenty-four','twenty-five','twenty-six','twenty-seven','twenty-eight','twenty-nine','thirty','thirty-one','thirty-two','thirty-three','thirty-four','thirty-five','thirty-six','thirty-seven','thirty-eight','thirty-nine','forty','forty-one ','forty-two','forty-three',' forty-four','forty-five',' forty-six',' forty-seven',' forty-eight',' forty-nine',' fifty','fifty-one','fifty-two','fifty-three','fifty-four ','fifty-five','fifty-six','fifty-seven','fifty-eight','fifty-nine','sixty']; var diff = curDate.getTime()-tem; if(diff<3600000){ var minute = Math.ceil(diff/60000); minute = numEng[minute-1]; tem = minute+' minutes ago'; }else if(diff<86400000){ var hour = Math.ceil(diff/3600000); hour = numEng[hour-1] tem = hour+' hours ago'; }else{ var date = dateFormat(tem); tem = date; } return tem; } function dateFormat(time){ var time = new Date(time); var year = time.getFullYear(); var month = time.getMonth()+1; var day = time.getDate(); function zeroFill(t){ if(t<10){ return '0'+t; }else{ return t; } } return year+"-"+zeroFill(month)+"-"+zeroFill(day); }