简体   繁体   中英

Creating a time array from a configuration

Hi all am very new to Javascript and Angular2. Am working on project which needs an array of timing based on a configuration which will be passed from backend. Basically the configuration consists of the following:

export const TIMEDATA: any = {
    start_time: "9",
    end_time: "16",
    interval: "30"
}

With this configuration, how can I come up with an array something like

Array = ["9:00", "9:30", "10:00", ...., "16:00"]

Any insights guys? Thanks in advance.

You can try using a loop to calculate the intervals:

 const leftpad = (str, padString, length) => { var s = str.toString(); while (s.length < length) s = padString + s; return s; } let timedata = { start_time: "9", end_time: "16", interval: "30" } let start_time = +timedata.start_time * 60; let end_time = +timedata.end_time * 60; let interval = +timedata.interval; let times = []; for (var i = start_time; i <= end_time; i += interval) { let h = Math.floor(i / 60); let m = i % 60; let time = [h, leftpad(m, '0', 2)].join(':'); times.push(time); } console.log(times); 

Here's a solution that uses lodash. To quickly use lodash in your project, include the script tag in the html page, then declare _ in the files that use it.

 let timedata = { start_time: "9", end_time: "16", interval: "30" } let start_time = +timedata.start_time * 60; let end_time = +timedata.end_time * 60; let interval = +timedata.interval; let times = _ .range(start_time, end_time + interval, interval) .map((time) => [ _.floor(time / 60), _.padStart(time % 60, 2, '0') ].join(':')); console.log(times); 
 <script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM