1. 程式人生 > 其它 >AntD日期選擇器元件DatePicker預設展示當前時間前一個週四

AntD日期選擇器元件DatePicker預設展示當前時間前一個週四

技術標籤:JSjsreact

util中寫個js方法

// 取當前時間的前一個週四
export const getThursday = () => {
  let now = new Date();
  let nowTime = now.getTime();
  let today = now.getDay(); // 今天是星期幾
  let oneDayLong = 24*60*60*1000;
  // 週五週六週日,展示本週四
  let nowDay1 = new Date(nowTime - (today-4)*oneDayLong);
  let year1 = nowDay1.getFullYear
(); let month1 = nowDay1.getMonth()+1; let day1 = nowDay1.getDate(); // 週一-週四,展示上週四 let nowDay2 = new Date(nowTime - (today+3)*oneDayLong); let year2 = nowDay2.getFullYear(); let month2 = nowDay2.getMonth()+1; let day2 = nowDay2.getDate(); let date = ''; if(today > 4 || today ===
0) { if(day1 < 10) { date = year1 + '-' + month1 + '-' + '0' + day1; } else { date = year1 + '-' + month1 + '-' + day1; } } else { if(day2 < 10) { date = year2 + '-' + month2 + '-' + '0' + day2; } else { date = year2 + '-' + month2 + '-' + day2; } }
return date; }

頁面中引用
(多的不寫了,在react中實現的)

// 頭
import { DatePicker } from 'antd';
import * as util from '../../crm-assets/js/utils.js';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
// constructor函式,預設時間
constructor(props) {
	super(props);
	this.state = {
		dateDefault: [moment(util.getThursday(), dateFormat), moment(util.getThursday(), dateFormat)],
	}
}
// componentDidMount預設渲染
componentDidMount() {
	moment.locale('zh-cn',{
       day: {
           dow: 5,
       },
	});
	this.getData();
}
// 傳值,getTable呼叫介面並返回
getData = async () => {
	let date = util.getThursday();
    this.setState({
        startTime: date,
		endTime: date,
    },()=>{
		this.getTable();
    });
}
render() {
	const { dateDefault } = this.state
	return (<>
		<RangePicker className='lob-select' onChange={this.changeDate} defaultValue={dateDefault} allowClear={false}/>
	</>)
}

今天是2020/12/18,星期五,前一個週四是昨天。選擇器預設展示:
在這裡插入圖片描述