JS 格式化时间

编程技术  /  houtizong 发布于 3年前   136
/** * 格式化时间 2013/6/13 by 半仙 [email protected] * 需要 pad 函数 * 接收可用的时间值. * 返回替换时间占位符后的字符串 * * 时间占位符:年 Y 月 M 日 D 小时 h 分 m 秒 s 重复次数表示占位数 * 如 YYYY 4占4位 YY 占2位<p></p> * MM DD hh mm ss 占2位,不足左侧补0. * * * 示例: * formatDate(date,'YYYY-MM-DD hh:mm:ss') * 2013-06-13 12:01:31<p></p> * * formarDate(date,'YY-M-D h:m:s') * 13-6-13 12:1:31 * * formarDate(date,'YYYY年MM月DD日 hh点mm分ss秒') * 2013年06月13日 12点01分31秒 */var formarDate = function(date, fromatStr) {    date = new Date(date);    date = {        Y: date.getFullYear().toString(),        M: date.getMonth() + 1 + "",        D: date.getDate().toString(),        h: date.getHours().toString(),        m: date.getMinutes().toString(),        s: date.getSeconds().toString()    };    var reg = '',        f1;    for (f1 in date) {        date[f1] = pad(date[f1], -2, "0");        if (f1 == "Y") {            continue;        }        reg = new RegExp(f1 + f1, 'g');        fromatStr = fromatStr.replace(reg, date[f1]);        reg = new RegExp(f1, 'g');        fromatStr = fromatStr.replace(reg, date[f1].replace(/^0/, ''));    }    // 替换年     fromatStr = fromatStr.replace(/YYYY/, date["Y"]);    fromatStr = fromatStr.replace(/YY/, date["Y"].substring(2));    return fromatStr;};//补位函数 // val 要修补的值// n 正数向右补 负数向左补// strPad 用以替补的字符串 默认 "0";var pad = function(val, n, strPad) {    strPad = strPad || "0";    n = n - 0;    var len = Math.abs(n) - val.toString().length,        ss = '';    if (len <= 0) {        return val;    }    ss = new Array(len + 1).join(strPad);    if (n < 0) {        val = ss + val;    } else {        val = val + ss;    }    return val;};

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客