微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

最全的时间转换 ts

各种类型 时间形式  转为字符串

time:时间值 

cFormat:    {y}-{m}-{d} {h}:{i}:{s}

                  {y}-{m}-{d} {h}:{i}:{s} {a}

                  {y}/{m}/{d} 

 
  1.  
    // Parse the time to string
     const parseTime = (
      time?: object | string | number | null,
      cFormat?: string
    ): string | null => {
      if (time === undefined || !time) {
        return null;
      }
      const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
      let date: Date;
      if (typeof time === "object") {
        date = time as Date;
      } else {
        if (typeof time === "string") {
          if (/^[0-9]+$/.test(time)) {
            // support "1548221490638"
            time = parseInt(time);
          } else {
            // support safari
            // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
            time = time.replace(new RegExp(/-/gm), "/");
          }
        }
        if (typeof time === "number" && time.toString().length === 10) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj: { [key: string]: number } = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
     
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
          console.log(value);
          return `星期${["日", "一", "二", "三", "四", "五", "六"][value]}` ;
        }
        return value.toString().padStart(2, "0");
      });
      return timeStr;
    };

    调用方法, 

    parseTime(new Date());
    // console :2020-11-30 10:36:24
     
    parseTime('2020-12-2');
    // console :2020-12-02 00:00:00
        
    parseTime(1604938866479);
    // console :2020-11-10 00:21:06
     
    parseTime("1604938866479");
    // console :2020-11-10 00:21:06
     
    parseTime("1604938866479","{y}-{m}-{d} {h}:{i}:{s}{a}");
    // console : 2020-11-10 00:21:06 星期二
     
    parseTime("1604938866479","{m}/{d}/{y}");
    // console : 12/02/2020
     
    parseTime(1);
    // console :1970-01-01 08:00:00
     
    parseTime(null);
    // console :null
     
    parseTime("");
    // console :null
     
    parseTime(undefined);
    // console :null
     
     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐