gpt4 book ai didi

javascript - 使用 JavaScript 创建日期和分钟数组

转载 作者:行者123 更新时间:2023-11-30 15:28:02 25 4
gpt4 key购买 nike

如何创建格式为 DD-MM-YYYY 的日期数组从今天开始,还有 1 天?

我猜是这样的

var dates = [];
var date = moment();

while (date <= date.clone().add(1, 'month')) {
dates.push(date.format('DD-MM-YYYY'));
date = date.clone().add(1, 'd');
}

但这是最好的方法吗?

我怎样才能用分钟做同样的事情?我想要一个 ['00:00', '00:05', '00:10', ..., '23:50', '23:55'] 的数组.

我猜是这样的

var minutes = [];
var time = moment('00:00', 'hh:mm');

while (time < time.clone().add(1, 'day')) {
minutes.push(time.format('hh:mm'));
time = time.clone().add(5, 'minutes');
}

为此使用 moment.js 并不重要,但我想它更容易。

最佳答案

由于这些可以是通用功能,因此您应该使它们可配置。

时间数组

对于 Time 数组,我想创建 moment 对象并操纵它的值将是一种资源浪费。您可以使用普通循环来做到这一点。

非时刻版

function getDoubleDigits(str) {
return ("00" + str).slice(-2);
}

function formatTime(h, m, is24Hr) {
var tmp = "";
if(is24Hr){
tmp =" " + (Math.floor(h/12) ? "p.m." : "a.m.")
h=h%12;
}
return getDoubleDigits(h) + ":" + getDoubleDigits(m) + tmp;;
}

function getTimeByInterval(interval, is24HrFormat) {
var times = []
for (var i = 0; i < 24; i++) {
for (var j = 0; j < 60; j += interval) {
times.push(formatTime(i, j, is24HrFormat))
}
}
return times.slice(0);
}

console.log(getTimeByInterval(5, false))
console.log(getTimeByInterval(5, true))


日期数组

由于您想要具有特定间隔的 2 个日期之间的日期,因此最好使它们可配置:

瞬间版

我什至在这个版本中使 format 可配置。这也可以在非时刻版本中完成,但我猜想(如何在纯 JS 中格式化日期)超出了问题的范围,所以不这样做。

function getDatesInrange(d1, d2, interval, format){
var dates = [];
while(d1.isBefore(d2)){
dates.push(d1.format(format));
d1.add(interval, "days");
}
console.log(dates)
return dates.slice(0)
}

getDatesInrange(moment(), moment().add(1, "month"), 1, "DD-MM-YYYY")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

非时刻版

function getDatesInrange(d1, d2, interval){
var dates = [];
while(+d1 < +d2){
dates.push(formateDate(d1));
d1.setDate(d1.getDate() + interval)
}
console.log(dates)
return dates.slice(0)
}

function formateDate(date){
return [getDoubleDigits(date.getDate()),
getDoubleDigits(date.getMonth() +1),
date.getFullYear()].join('-')
}

var startDate = new Date();
var endDate = new Date();
endDate.setMonth(endDate.getMonth() + 1);
getDatesInrange(startDate, endDate, 1)

function getDoubleDigits(str) {
return ("00" + str).slice(-2);
}

关于javascript - 使用 JavaScript 创建日期和分钟数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42665289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com