您的位置:首页 > Web前端 > JavaScript

JavaScript常用方法整理收集

2017-02-13 16:10 405 查看
1.时间处理以及时间格式化---timeformat

  方法介绍:根据需求将后台时间字符串转换为需要的时间格式进行显示

 参数说明;date:时间字符串  format:需要显示的时间格式规则

    <!doctype html>

<html lang="en">

 <head>

  <meta charset="UTF-8">

  <meta name="Generator" content="EditPlus®">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

  <title>Document</title>

  <script>

     function formatDate(date, format) {   

    if (!date) return;   

    if (!format) format = "yyyy-MM-dd";   

    switch(typeof date) {   

        case "string":   

            date = new Date(date.replace(/-/, "/"));   

            break;   

        case "number":   

            date = new Date(date);   

            break;   

    }    

    if (!date instanceof Date) return;   

    var dict = {   

        "yyyy": date.getFullYear(),   

        "M": date.getMonth() + 1,   

        "d": date.getDate(),   

        "H": date.getHours(),   

        "m": date.getMinutes(),   

        "s": date.getSeconds(),   

        "MM": ("" + (date.getMonth() + 101)).substr(1),   

        "dd": ("" + (date.getDate() + 100)).substr(1),   

        "HH": ("" + (date.getHours() + 100)).substr(1),   

        "mm": ("" + (date.getMinutes() + 100)).substr(1),   

        "ss": ("" + (date.getSeconds() + 100)).substr(1)   

    };       

    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {   

        return dict[arguments[0]];   

    });                   

}   

  

alert(formatDate("2010-04-30", "yyyy-MM-dd HH:mm:ss"));   

alert(formatDate("2010-4-29 1:50:00", "MM-dd HH:mm:ss"));  

  </script>

 </head>

 <body>

  

 </body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 格式化