Bre*_*ody 22 javascript arrays
我试图Date
在整个24小时内每隔X分钟创建一个时间阵列(字符串,而不是对象).例如,对于5分钟的间隔,阵列将是:
['12:00 AM', '12:05 AM', '12:10 AM', '12:15 AM', ..., '11:55 PM']
Run Code Online (Sandbox Code Playgroud)
我的快速而肮脏的解决方案是使用3个嵌套for
循环:
var times = []
, periods = ['AM', 'PM']
, hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
, prop = null
, hour = null
, min = null;
for (prop in periods) {
for (hour in hours) {
for (min = 0; min < 60; min += 5) {
times.push(('0' + hours[hour]).slice(-2) + ':' + ('0' + min).slice(-2) + " " + periods[prop]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这会输出所需的结果,但我想知道是否有更优雅的解决方案.有没有办法做到这一点:
Har*_*eet 27
如果间隔仅以分钟[0-60]设置,则评估以下解决方案,无需创建日期对象并在单循环中:
var x = 5; //minutes interval
var times = []; // time array
var tt = 0; // start time
var ap = ['AM', 'PM']; // AM-PM
//loop to increment the time and push results in array
for (var i=0;tt<24*60; i++) {
var hh = Math.floor(tt/60); // getting hours of day in 0-24 format
var mm = (tt%60); // getting minutes of the hour in 0-55 format
times[i] = ("0" + (hh % 12)).slice(-2) + ':' + ("0" + mm).slice(-2) + ap[Math.floor(hh/12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt = tt + x;
}
console.log(times);
Run Code Online (Sandbox Code Playgroud)
Ram*_*ose 13
分配结果数组以避免推送,参数验证和区域设置细节的开销,尽管如此:
function generate_series(step) {
var dt = new Date(1970, 0, 1, 0, 0, 0, 0),
rc = [];
while (dt.getDate() == 1) {
rc.push(dt.toLocaleTimeString('en-US'));
dt.setMinutes(dt.getMinutes() + step);
}
return rc;
}
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴https://jsfiddle.net/m1ruw1x6/35/
在Moment.js的帮助下,以下内容非常灵活.
此代码使用
没有错误处理,所以你可以传入愚蠢的参数,但它得到了重点.:-D
该desiredStartTime
参数需要hh:mm
格式化时间.
该period
参数接受任何moment.duration
输入.
const timelineLabels = (desiredStartTime, interval, period) => {
const periodsInADay = moment.duration(1, 'day').as(period);
const timeLabels = [];
const startTimeMoment = moment(desiredStartTime, 'hh:mm');
for (let i = 0; i <= periodsInADay; i += interval) {
startTimeMoment.add(i === 0 ? 0 : interval, period);
timeLabels.push(startTimeMoment.format('hh:mm A'));
}
return timeLabels;
};
/* A few examples */
const theDiv = document.getElementById("times");
let content;
content = JSON.stringify(timelineLabels('18:00', 2, 'hours'))
theDiv.appendChild(document.createTextNode(content));
theDiv.appendChild(document.createElement("p"));
content = JSON.stringify(timelineLabels('06:00', 30, 'm'))
theDiv.appendChild(document.createTextNode(content));
theDiv.appendChild(document.createElement("p"));
content = JSON.stringify(timelineLabels('00:00', 5, 'minutes'))
theDiv.appendChild(document.createTextNode(content));
theDiv.appendChild(document.createElement("p"));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<div id="times"></div>
Run Code Online (Sandbox Code Playgroud)
如果您有权访问moment
,则可以始终执行以下操作:
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 A'));
hours.push(
moment({
hour,
minute: 30
}).format('h:mm A')
);
}
Run Code Online (Sandbox Code Playgroud)
结果是以下数组:
["12:00 AM", "12:30 AM", "1:00 AM", "1:30 AM", "2:00 AM", "2:30 AM", "3:00 AM", "3:30 AM", "4:00 AM", "4:30 AM", "5:00 AM", "5:30 AM", "6:00 AM", "6:30 AM", "7:00 AM", "7:30 AM", "8:00 AM", "8:30 AM", "9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00 PM", "12:30 PM", "1:00 PM", "1:30 PM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM", "4:00 PM", "4:30 PM", "5:00 PM", "5:30 PM", "6:00 PM", "6:30 PM", "7:00 PM", "7:30 PM", "8:00 PM", "8:30 PM", "9:00 PM", "9:30 PM", "10:00 PM", "10:30 PM", "11:00 PM", "11:30 PM"]
Run Code Online (Sandbox Code Playgroud)
你只需要一个循环,遵循这种方法
var d = new Date(); //get a date object
d.setHours(0,0,0,0); //reassign it to today's midnight
Run Code Online (Sandbox Code Playgroud)
现在继续添加5分钟,直到d.getDate()
值发生变化
var date = d.getDate();
var timeArr = [];
while ( date == d.getDate() )
{
var hours = d.getHours();
var minutes = d.getMinutes();
hours = hours == 0 ? 12: hours; //if it is 0, then make it 12
var ampm = "am";
ampm = hours > 12 ? "pm": "am";
hours = hours > 12 ? hours - 12: hours; //if more than 12, reduce 12 and set am/pm flag
hours = ( "0" + hours ).slice(-2); //pad with 0
minute = ( "0" + d.getMinutes() ).slice(-2); //pad with 0
timeArr.push( hours + ":" + minute + " " + ampm );
d.setMinutes( d.getMinutes() + 5); //increment by 5 minutes
}
Run Code Online (Sandbox Code Playgroud)
此代码段根据区域设置生成范围,因此您无需手动处理 AM/PM。默认情况下,它将使用浏览器语言,但您可以传递用户选择的语言。
function getTimeRanges(interval, language = window.navigator.language) {
const ranges = [];
const date = new Date();
const format = {
hour: 'numeric',
minute: 'numeric',
};
for (let minutes = 0; minutes < 24 * 60; minutes = minutes + interval) {
date.setHours(0);
date.setMinutes(minutes);
ranges.push(date.toLocaleTimeString(language, format));
}
return ranges;
}
console.log('English', getTimeRanges(30, 'en'));
console.log('Russian', getTimeRanges(30, 'ru'));
Run Code Online (Sandbox Code Playgroud)