JS实现当前时间戳的时分秒置0

465 阅读1分钟

效果:获取当前时间戳,起始时间时分秒置00:00:00

image.png

解决办法一:

大多数解决办法是将当前时间戳转换成日期,再结合些字符串处理方法,将小时,分钟转换成00:00;

代码:

function formatTimeToMidnight(timestamp) { 
    const date = new Date(timestamp); 
    date.setHours(0); 
    date.setMinutes(0);
    const year=date.getFullYear()
    const month=date.getMonth()+1
    const day=date.getDate()
    const hours = String(date.getHours()).padStart(2, '0'); 
    const minutes = String(date.getMinutes()).padStart(2, '0'); 
    return year +'-'+ month +'-'+ day +' '+ hours + ':' + minutes ; 
} 

const timestamp = new Date().getTime(); // 用于转换的时间戳 
const midnightFormat = formatTimeToMidnight(timestamp); 
console.log(midnightFormat); // 输出 "2024-5-23 00:00"

解决办法二:

直接利用moment,将里面的时分秒置成0

代码

const nowTime = new Date()
<Formltem
    label="时间段:
    name="time"
    initialValue={[
        moment(
            new Date(
                nowTime.getFullYear(),
                nowTime .getMonth()
                nowTime.getDate(),
                0,
                0,
                0
               )
             ),
        moment(nowTime.getTime()),
      ]}
 >
  <RangePicker
    showTime={{format:'HH:mm'}}
    format="YYYY-MM-DD HH: mm'
    onOk={onOk}
   />
</Formltem>