如何创建一个间隔半小时的时间数组而不是在变量中声明 [英] how to create an array of times with half hour intervals instead of declare in variable
本文介绍了如何创建一个间隔半小时的时间数组而不是在变量中声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在下面有一个长常量值,是否可以在打字稿中创建函数以减少长常量.
i have an long const values below like this ,is it possible to create in function in typescript to reduce a long const.
export const DepartTime =
['00.00', '00.30', '01.00', '01.30', '02.00', '02.30', '03.00', '03.30', '04.00', '04.30', '05.00', '05.30', '06.00', '06.30', '07.00', '07.30', '08.00', '08.30', '09.00', '09.30', '10.00', '10.30', '11.00', '11.30', '12.00', '12.30', '13.00',
'13.30', '14.00', '14.30', '15.00', '15.30', '16.00', '16.30', '17.00', '17.30', '18.00', '18.30', '19.00', '19.30',
'20.00', '20.30', '21.00', '21.30', '22.00', '22.30', '23.00', '23.30'
];
这些值需要在 angular 下拉列表中绑定.
These values need to be bind in angular dropdown.
export class SelectOverviewExample implements OnInit {
days=[];
times =[];
ngOnInit(){
[...this.days] = weekdays;
[...this.times]=DepartTime;
}
在 html 中.
<mat-form-field>
<mat-select placeholder="select Weekdays">
<mat-option *ngFor="let time of times" [value]="time">
{{time}}
</mat-option>
</mat-select>
</mat-form-field>
或任何第三方框架都支持
or any third party framework will support
我已经尝试过这个并得到以下结果:
I have tried this and getting below result:
var toInt = time => ((h,m) => h*2 + m/30)(...time.split(':').map(parseFloat)),
toTime = int => [Math.floor(int/2), int%2 ? '30' : '00'].join(':'),
range = (from, to) => Array(to-from+1).fill().map((_,i) => from + i),
eachHalfHour = (t1, t2) => range(...[t1, t2].map(toInt)).map(toTime);
console.log(eachHalfHour('00:00', '23:30'))
但我需要个位数以 00:00,00:30,01.00,01.30 ... 09.30 开头.O/p
But i need single digit have start with 00:00,00:30,01.00,01.30 ... 09.30. O/p
通过使用 moment js,我得到了一个解决方案,但需要 0 前缀来表示个位数
by using moment js , i have get a solution but need 0 prefix for single digits
const locale = 'en'; // or whatever you want...
const hours = [];
moment.locale(locale); // optional - can remove if you are only dealing with one locale
for(let hour = 0; hour < 24; hour++) {
hours.push(moment({ hour }).format('H:mm'));
hours.push(
moment({
hour,
minute: 30
}).format('H:mm')
);
}
console.log(hours);
推荐答案
你可以使用除以 2.
let DepartTime = [...Array(48)].map((e, i) => {
return (i/2<10 ? '0' : '') + (i/2 - i/2 % 1) + (i/2 % 1 != 0 ? '.30' : '.00');
});
console.log(DepartTime);
这篇关于如何创建一个间隔半小时的时间数组而不是在变量中声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文