日期格式化代码

封装按指定格式显示日期的代码

function timeFormat(time, format) {
  let o = {
    'M+': time.getMonth() + 1, // 月份
    'd+': time.getDate(), // 日
    'h+': time.getHours(), // 小时
    'm+': time.getMinutes(), // 分
    's+': time.getSeconds(), // 秒
    'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
    'S': time.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
  }
  return format;
}
//调用
timeFormat(date, 'yyyy-MM-dd');

秒数转为时:分:秒

function formatDuration(duration){
  if(duration < 60) return duration + 's';
  var minutes = parseInt(duration / 60);
  var seconds = duration % 60;
  if(minutes < 60){
    return minutes + ':' + seconds;
  }else{
    var hour = parseInt(minute / 60);
    minutes = minutes % 60;
    return hour + ':' + minutes + ':' + seconds;
  }
}

获取UTC时间

function utcTime(date){
let time = new Date(date);
let y = time.getFullYear(), M = time.getMonth(), d = time.getDate(), h = time.getHours(), m= time.getMinutes(), s = time.getSeconds();
return Date.UTC(y, M, d, h, m, s);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,050评论 3 119
  • 1.参考了阿宝妈关于“不”语言的转换,很受启发。将“不”转换为启发式提问/选择性提问,明天试用起来 2.鼓励性语言...
    荐佼阅读 775评论 0 0
  • 在生活中,某些人做的某些事一定会让我们特别讨厌,尽管自己尽力掩饰,也会在无意中针对她(他),但是时间久了,你就会发...
    安慕妮阅读 2,507评论 0 0
  • 我们从小到大有好多朋友,朋友是一个知心的,倾诉的,好朋友是我们自己创造的。有人说:如果一个身材很好,又很漂亮,又很...
    猫咪宝贝猫咪宝贝阅读 1,794评论 0 0