zoukankan      html  css  js  c++  java
  • 【小分享】Date对象封装,时间格式化函数time()

    今天再来分享下Date的应用知识点

    先看效果,类似于php里边的time('yyyy-mm-dd')用法,但是我这里没有完全依照php的参数格式来,如果有需要稍微修改一下就行。

    首先,明确需要用到的参数:

    1、时间戳,就是你需要格式化的时间戳;

    2、格式字符串,类似于“yy-mm-dd”;

    具体做法无非就是获取到“年、月、日、时、分、秒、星期”,然后做一对blabla的处理,不啰嗦,先上代码:

     1 function formateDate(strTime, format, needMap) {
     2     strTime = Number(strTime);
     3     format = format || 'Y-M-D H:I:S';
     4     var date = new Date(strTime);
     5     var dateMap = {
     6         y: (date.getFullYear()+'').slice(2),
     7         Y: date.getFullYear(),
     8         M: date.getMonth() + 1,
     9         D: date.getDate(),
    10         h: date.getHours()%12,
    11         H: date.getHours(),
    12         i: date.getMinutes(),
    13         s: date.getSeconds(),
    14         I: date.getMinutes() > 9 ? date.getMinutes() : ('0' + date.getMinutes()),
    15         S: date.getSeconds() > 9 ? date.getSeconds() : ('0' + date.getSeconds()),
    16         A: date.getHours() >= 12 ? 'pm' : 'am',
    17         w: date.getDay(),
    18         W: ['日','一','二','三','四','五','六'][date.getDay()]
    19     };
    20     for (var k in dateMap) {
    21         format = format.replace(new RegExp(k, 'g'), dateMap[k]);
    22     }
    23     if (needMap) {
    24         return dateMap;
    25     }
    26     return format;
    27 }

    这里格式字符串未严格使用php的方式,采用了大小写来区分

    y: 2位数年(91)
    Y: 4位数年(1991)
    M: 月份(10)
    D: 日(15)
    H: 24小时格式(19)
    h: 12小时格式(7)
    I: 2位分钟(05)
    i: 1位分钟(5)
    S: 2位秒(09)
    s: 1位秒(9)
    W: 中文周几(三)
    w: 数字周几(3)
    A: 上午/下午(am/pm)

    使用示例:

    • formateDate(Date.now(), 'Y-M-D H:I:S') ==> "2016-10-26 15:07:09"
    • formateDate(Date.now(), 'Y-M-D H:i:s'==> "2016-10-26 15:7:9"
    • formateDate(Date.now(), 'y-M-D | .A h:I:S') ==> "16-10-26 | .pm 3:49:32"
    • formateDate(Date.now(), 'Y-M-D H:I:S | 周W | 周w') ==> "2016-10-26 15:52:28 | 周三 | 周3"

    时间处理大家都懂,不啰嗦,简单说下“时间格式字符串”处理

    这里其实就是多次把传进来的字符串做replace处理,把格式字符串中合法的字符串用对应的时间数据替换,最后返回就是我们需要的格式了

    另外,还有最后一个参数,是作为debug参数用的,true的时候返回整个dateMap。

    就酱紫吧~~~

  • 相关阅读:
    maven-eclipse-plugin downloadSources downloadJavadocs
    maven的resources插件
    Intellij IDEA 添加项目依赖
    git 代码统计
    windows查看局域网ip
    Spring Boot学习笔记---Spring Boot 基础及使用idea搭建项目
    git push fatal: HttpRequestException encountered. An error occurred while sending the request
    ubuntu15中tomcat开机自动启动
    ubuntu15 设置静态ip && centos7设置静态ip
    ubuntu15.10 下时间同步
  • 原文地址:https://www.cnblogs.com/ufex/p/6394679.html
Copyright © 2011-2022 走看看