[英]MomentJS Parsing big data string
所以,我有這種數據startTime: Fri Dec 28 2018 01:15:00 GMT+0200 (Eastern European Standard Time)
和這個endTime: Mon Dec 31 2018 02:15:00 GMT+0200 (Eastern European Standard Time)
數據始終采用這種格式。 我需要解析它,這樣我才能在startTime和endTime的時間(在這種情況下為1:15-2:15)的每一天中,在startTime和endTime之間的所有日期中都有一個對象數組。 我有一個答案是
function toDays(startDateString, endDateString) {
const startDate = moment(startDateString, 'dddd MMM DD YYYY');
const endDate = moment(endDateString, 'dddd MMM DD YYYY');
const dates = [];
while(startDate.isSameOrBefore(endDate, 'day')) {
let currentDay = startDate.format('dddd');
dates[currentDay] = [];
dates[currentDay].push({start:'9:00', end:'18:00'});
startDate.add(1, 'days');
}
return dates;
}
const result = toDays('Mon Dec 24 2018', 'Fri Dec 28 2018');
console.log(result);
但是我不能真正使用它,我不確定如何解決此問題,因為我之前從未使用過。
將天名添加到您創建的新對象中,作為屬性,例如day
然后將整個對象推入數組
更改
dates[currentDay] = [];
dates[currentDay].push({start:'9:00', end:'18:00'});
至
dates.push({ day: currentDay, start:'9:00', end:'18:00'})
如果我正確理解了這個問題,那么您可能很難確定如何解析格式startTime: Fri Dec 28 2018 01:15:00 GMT+0200 (Eastern European Standard Time)
? 如果確實如此,那么我認為以下代碼可能會有所幫助:
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.js'></script>
<script>
function toDays(startDateString, endDateString) {
const formatString = 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ [(Eastern European Standard Time)]';
const startDate = moment(startDateString, formatString).utcOffset("+02:00");
const endDate = moment(endDateString, formatString).utcOffset("+02:00");
const start = startDate.format('H:mm');
const end = endDate.format('H:mm');
const dates = [];
while(startDate.isSameOrBefore(endDate, 'day')) {
let currentDay = startDate.format('dddd');
dates.push({day: currentDay, start: start, end: end});
startDate.add(1, 'days');
}
return dates;
}
const result = toDays('Fri Dec 28 2018 01:15:00 GMT+0200 (Eastern European Standard Time)', 'Mon Dec 31 2018 02:15:00 GMT+0200 (Eastern European Standard Time)');
console.log(result);
</script>
要點是線const formatString = 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ [(Eastern European Standard Time)]';
解析您正確提供的日期格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.