时间戳的整块与时间的整块错位

131 阅读1分钟

image.png 需求 需要限制时间范围

首次尝试

let now=new Date().getTime()
let oneday=24*60*60*1000
//打算 取余后得到不足一天的部分 补齐 预期得到第二天0点
now = now+oneday-now%oneday
得到的却是第二天8点
new Date(1671667200000)
Thu Dec 22 2022 08:00:00 GMT+0800 (GMT+08:00)

错误的根源在于 我国在东八区 时间戳是基于1970年1月1日8点的
new Date(0)
Thu Jan 01 1970 08:00:00 GMT+0800 (GMT+08:00)
若想通过取余填补 还得减去8小时
时间戳按天整块整块划分 和 日期的整天整天 是错位的

now+oneday-now%oneday-8*60*60*1000
new Date(1671638400000)
Thu Dec 22 2022 00:00:00 GMT+0800 (GMT+08:00)

正确实践

  • toLocaleDateString() 根据本地时间格式,把 Date 对象的日期部分转换为字符串。
  • 获取 23点59分59秒:new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1
  • 获取 00点00分00秒:new Date(new Date().toLocaleDateString()).getTime()
        <el-date-picker v-model="searchParam.timeRange"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']"
                        :picker-options="pickerOptions"
                        prefix-icon="el-icon-date"
                        size="mini">
        </el-date-picker>
      
 data(){return{---
     pickerOptions: {
       disabledDate(date) {
         let today = new Date(new Date().toLocaleDateString()).getTime()+24 * 60 * 60 * 1000 -1
         return date.getTime() > today
        },
      },