用JS写一个简单的时间格式化函数,可把uct时间设置为本地时间,并且格式化

其实已经有好用的时间格式化工具了,http://momentjs.cn/

写这个时间格式化函数主要是满足一个需求:将uct时间转化为本地时间且格式化时间;

function formatTime(time) {
  return time < 10 ? "0" + time : time;
};
// 参数 时间字符串, 格式化的样式
function localTime(time, formatString="yyyy-MM-dd hh:mm:ss"){
  let date = new Date(time);
  // 将utc时区时间转为当前本地时间
  let currentTimeZoneOffsetInHours = date.getTimezoneOffset()/60;
  date.setHours(date.getHours()-currentTimeZoneOffsetInHours)

  formatString = formatString.replace("yyyy",date.getFullYear())
                  .replace("MM", date.getMonth() + 1)
                  .replace("dd", formatTime(date.getDate()))
                  .replace("hh", formatTime(date.getHours()))
                  .replace("mm", formatTime(date.getMinutes()))
                  .replace("ss", formatTime(date.getSeconds()));
  return formatString;
};

export default {
  localTime: localTime
};

更新一下:

因为我们的项目涉及到了多个时间组件,比如有日期+时间的组件,单纯的时间组件,要求需要存零时区的时间,数据到前端的时候显示当地时间。项目里新引入了moment.js

于是更新了一下这个文件如下,让它用起来更方便。

import moment from 'moment'

function localDate(date) {
  // 将utc时区时间转为当前本地时间,返回moment对象,然后使用format方法格式化时间
  if(moment(date).isValid()){
    return moment.utc(date).local();
  }
  return ;
}

function utcDate(date, componentType){
  // 将本地时间转为utc时间,按规定的格式化
  switch(componentType){
    case "DateInput":
      return moment(date).utc().millisecond(0).format().replace("Z","");
    case "PureTime":
      return moment(date).utc().millisecond(0).format("HH:mm:ss.SSS")
    case "PureDate":
      return moment(date).utc().millisecond(0).format("YYYY-MM-DD")
  }
  return ;
}

export default {
  localDate,
  utcDate
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值