js 输出固定时间格式

 

 
/**
* 将时间转换成固定格式输出
* new Date().toFormat('yyyy-MM-dd HH:mm:ss');
* new Date().toFormat('yyyy/MM/dd hh:mm:ss');
* 只支持关键字(yyyy、MM、dd、HH、hh、mm、ss)HH:表示24小时,hh表示12小时
*/
Date.prototype.toFormatString=function(format){
    var formatstr = format;
    if(format != null && format != ""){
        //设置年
        if(formatstr.indexOf("yyyy") >=0 ){
            formatstr = formatstr.replace("yyyy",this.getFullYear());
        }
        //设置月
        if(formatstr.indexOf("MM") >=0 ){
            var month = this.getMonth() + 1;
            if(month < 10){
                month = "0" + month;
            }
            formatstr = formatstr.replace("MM",month);
        }
        //设置日
        if(formatstr.indexOf("dd") >=0 ){
            var day = this.getDay();
            if(day < 10){
                day = "0" + day;
            }
            formatstr = formatstr.replace("dd",day);
        }
        //设置时 - 24小时
        var hours = this.getHours();
        if(formatstr.indexOf("HH") >=0 ){
            if(month < 10){
                month = "0" + month;
            }
            formatstr = formatstr.replace("HH",hours);
        }
        //设置时 - 12小时
        if(formatstr.indexOf("hh") >=0 ){
            if(hours > 12){
                hours = hours - 12;
            }
            if(hours < 10){
                hours = "0" + hours;
            }
            formatstr = formatstr.replace("hh",hours);
        }
        //设置分
        if(formatstr.indexOf("mm") >=0 ){
            var minute = this.getMinutes();
            if(minute < 10){
                minute = "0" + minute;
            }
            formatstr = formatstr.replace("mm",minute);
        }
        //设置秒
        if(formatstr.indexOf("ss") >=0 ){
            var second = this.getSeconds();
            if(second < 10){
                second = "0" + second;
            }
            formatstr = formatstr.replace("ss",second);
        }
    }
    return formatstr;
}

  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值