Javascript 使用日期范围和时间间隔创建角度日期数组
我试图为用户创建一个选项,以获取用户选择的两个日期(每天8:00-17:00)之间可能的访问时间 例如:在9月1日至4日之间,返回[1.09.20 8:00,1.09.20 8:15…,4.09.20 16:45] 我最初的想法是创建两个循环,其中一个循环重复几天,第二次,但很快我意识到Date并没有真正与我合作。后来,我偶然发现了这段代码,它只生成了几天,没有遍历时间,但它对我不起作用:Javascript 使用日期范围和时间间隔创建角度日期数组,javascript,angular,date,datetime,Javascript,Angular,Date,Datetime,我试图为用户创建一个选项,以获取用户选择的两个日期(每天8:00-17:00)之间可能的访问时间 例如:在9月1日至4日之间,返回[1.09.20 8:00,1.09.20 8:15…,4.09.20 16:45] 我最初的想法是创建两个循环,其中一个循环重复几天,第二次,但很快我意识到Date并没有真正与我合作。后来,我偶然发现了这段代码,它只生成了几天,没有遍历时间,但它对我不起作用: let dates: Date[]; const theDate = new Date(from); wh
let dates: Date[];
const theDate = new Date(from);
while (theDate < to) {
dates = [...dates, new Date(theDate)];
theDate.setDate(theDate.getDate() + 1);
}
return dates;
let日期:日期[];
const theDate=新日期(从);
while(日期
控制台:(开始日期和结束日期都在工作,在日志中显示为已定义)
太阳2020年8月23日00:00:00 GMT+0200(中欧夏季时间)
2020年8月29日星期六00:00:00 GMT+0200(中欧夏季时间)
core.js:4197 ERROR-TypeError:undefined不可iterable(无法读取属性符号(Symbol.iterator))
在VisitService.getdates之间(visit.service.ts:31)
在PatientVisitComponent.findVisits(患者就诊.component.ts:88)
在PatientVisitComponent\u模板\u输入\u单击\u 28\u监听器(patient visit.component.html:49)
在executeListenerWithErrorHandling上(core.js:14315)
在wrapListenerIn_markDirtyAndPreventDefault(core.js:14350)
在HTMLInputElement。(platformbrowser.js:582)
在ZoneDelegate.invokeTask(zone evergreen.js:399)
我对任何预构建工具都持开放态度,我只需要稍后过滤此阵列,排除已经使用的时间(保存为日期,但我可以更改),并让用户选择一个来预订访问
编辑:哎呀,忘了添加=[];到日期,所以它有效,但只适用于几天。有没有更优雅的解决时间问题的方法?我更喜欢
时刻
而不是日期
对象,但就我们现在的情况而言,下面是我如何处理日期
对象的。因此,首先,Date
对象接受格式(年、月、日)的输入。为了正确输出日期,您必须遵循此步骤
let fromMonth = "12";
let fromDay = "02";
let fromYear = "2020";
let toMonth = "12";
let toDay = "05";
let toYear = "2020";
let from = new Date(fromYear+"-"+fromMonth+"-"+fromDay);
let to = new Date(toYear+"-"+toMonth+"-"+toDay);
let dates = [];
while (from < to) {
dates = [...dates, new Date(from)];
from.setDate(from.getDate() + 1);
}
console.log(dates);
let fromMonth = "12";
let fromDay = "02";
let fromYear = "2020";
let toMonth = "12";
let toDay = "05";
let toYear = "2020";
let from = new Date(fromYear+"-"+fromMonth+"-"+fromDay);
let to = new Date(toYear+"-"+toMonth+"-"+toDay);
let dates = [];
while (from < to) {
dates = [...dates, new Date(from)];
from.setDate(from.getDate() + 1);
}
console.log(dates);
let fromDate = "05-12-2020";
let toDate = "11-12-2020";
//No need to input date in specific format with moment
let from = moment(fromDate).format('DD-MM-YYYY');
let to = moment(toDate).format('DD-MM-YYYY');
let dates = [];
while (moment(from).isBefore(to)) {
dates = [...dates, new Date(from)];
from = moment(from).add(1,'days'). format('DD-MM-YYYY'); //====> equivalent to from.setDate(from.getDate() + 1);
}
console.log(dates);