转换成时间戳
// 转换成时间戳
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*12)
const 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');
}
}