写一个时间处理的库

本文基于我对 ms 这个库的阅读。这个库的代码一共一百多行,完整看下来也就十几分钟,但是这个库非常的有用。这个库的核心是,将毫秒和可读的表示时间的字符串相互转换。这个库还是存在一些缺陷,比如在毫秒转字符串时用了近似(其实也不算是缺陷,而是有意为之)。

首先定义几个常量,分别为一秒,一分,一时,一日,一年对应的毫秒数。

var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24,
y = d * 365.25  

然后我们写字符串转毫秒的方法

function parse(str){
  var arr = str.split(' '),
  res = 0
  arr.forEach(function(a){
    var match = /^((?:\d+)?\.?\d+) *(y|d|h|m|s|ms)?$/i.exec(a)
    var n = parseFloat(match[1]);

    var type = match[2].toLowerCase();
    switch(type){
      case 'y':
        res += n*y;
        break;
      case 'd':
        res += n*d;
        break;
      case 'h':
        res += n*h;
        break;
      case 'm':
        res += n*m;
        break;
      case 's':
        res += n*s;
        break;
      case 'ms':
        res += n;
    }
  })
  return res
}

测试一下

parse('2d 10h 5s')    //208805000

然后我们写毫秒转字符串的方法

function tostr(ms){
  if(ms === 0) return "";
  if(ms >= d) return Math.round(ms / d)+'d ' + tostr(ms%d);
  if(ms >= h) return Math.round(ms / h)+'h ' + tostr(ms%h);
  if(ms >= m) return Math.round(ms / m)+'m ' + tostr(ms%m);
  if(ms >= s) return Math.round(ms / s)+'s ' + tostr(ms%s);
  return ms + 'ms';
}

console.log(tostr(610000000))

封装

这么多全局变量实在太糟糕,用IIFE封装一下

var ms = (function(){
  var s = 1000,
  m = s*60,
  h = m*60,
  d = h*24,
  y = d*365.25
  function parse(str){
    var arr = str.split(' '),
    res = 0
    arr.forEach(function(a){
      var match = /^((?:\d+)?\.?\d+) *(y|d|h|m|s|ms)?$/i.exec(a)
      var n = parseFloat(match[1]);

      var type = match[2].toLowerCase();
      switch(type){
        case 'y':
          res += n*y;
          break;
        case 'd':
          res += n*d;
          break;
        case 'h':
          res += n*h;
          break;
        case 'm':
          res += n*m;
          break;
        case 's':
          res += n*s;
          break;
        case 'ms':
          res += n;
      }
    })
    return res
  }

  function tostr(ms){
    if(ms === 0) return "";
    if(ms >= d) return Math.round(ms / d)+'d ' + tostr(ms%d);
    if(ms >= h) return Math.round(ms / h)+'h ' + tostr(ms%h);
    if(ms >= m) return Math.round(ms / m)+'m ' + tostr(ms%m);
    if(ms >= s) return Math.round(ms / s)+'s ' + tostr(ms%s);
    return ms + 'ms';
  }

  return function(val, options){
    options = options || {};
    if ('string' == typeof val) return parse(val);
    return tostr(val);
  };
})()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,397评论 19 139
  • :每天交易流水200万,日赚十余万…… 2017-11-05 清流Club 网贷天眼 这是一篇来电投稿,因此会以问...
    爱吃番茄great阅读 1,722评论 0 0