封装的简单时间转换,可拓展

转换成时间戳

// 转换成时间戳
export function timeStamp(time: any) {
  return new Date(time).getTime()
}

可以转换的日期格式为:
1. “2018/1/1 8:00:00”;
2. “2018,1,1 8:00:00”;
3. “2018-1-1 8:00:00”; - 中间不能有空格,如果有空格需要过滤掉
4. “2019-01-08T00:51:02.000+0000” ;
其中年份为必填,其余的都可以省略,
月/日不填的话默认是1月1日
时:分:秒不填:
第1.2种格式默认是00:00:00,
第3.种格式默认是08:00:00

时间格式化

// 时间格式化
export function timeFormatting(date:number) {
  const year = new Date(date).getFullYear()
  const month = new Date(date).getMonth() + 1
  const day = new Date(date).getDate()
  const hour = new Date(date).getHours() < 10 ? '0' + new Date(date).getHours() : new Date(date).getHours()
  const minutes = new Date(date).getMinutes() < 10 ? '0' + new Date(date).getMinutes() : new Date(date).getMinutes()
  const seconds = new Date(date).getSeconds() < 10 ? '0' + new Date(date).getSeconds() : new Date(date).getSeconds()
  return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`
}
// 返回例:'2020-1-1 00:00:00'

这里是按需导出,在需要的位置按需引入传值即可

更多时间转换参考:js中时间日期与时间戳相互转换的方法

在案例中使用

使用 ant design 中的时间组件 RangePicker


  // 时间选择
  public handleChange = (value, dateStrings) => {
     console.log(value[0]._d)  web格式时间,清空时间时会因为拿不到报错
     console.log(dateStrings);  返回的数组包含两个字符串类型时间格式,可拿来渲染或时间操作
    // console.log(timeStamp(dateStrings[0]));
    
     需要得出时间范围,因时区原因,前后各换算半天(1000*60*60*12const timeBigen = timeStamp(dateStrings[0]) - 43200000
    const timeEnd = timeStamp(dateStrings[1]) + 43200000
    
     对数据数组进行过滤操作,具体逻辑看需求来
    (准备一个包含所有数据的数组,方便返回所有数据,或者重新请求数据)
    if (this.state.projectList.length !== 0) {
      const newProjectList = this.state.projectList.filter(item => timeStamp(item.start_time) >= timeBigen && timeStamp(item.end_time) <= timeEnd)
      this.setState(() => ({projectList: newProjectList}))
      console.log(newProjectList,'projectList');
      console.log(this.state.projectList)
    } else {
      const newProjectList = this.state.projectListAll.filter(item => timeStamp(item.start_time) >= timeBigen && timeStamp(item.end_time) <= timeEnd)
      this.setState(() => ({projectList: newProjectList}))
      console.log(newProjectList,'all');
    }
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值