我有代码在一个日期范围内生成随机日期,它给我的日期在记录时会产生这种格式:
Wed Sep 25 2019 05:00:00 GMT+0500 (Pakistan Standard Time)
我只想获取没有时区和 Day 的日期,具体如下:
2019-09-25
我正在尝试使用以下代码获取指定日期之间的随机日期:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length, temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1; }
console.log(shuffle(dateArr));
这不是一个重复的问题,因为我正在尝试实现不同且非常具体的合成。
最佳答案
一个解决方案是通过自定义格式函数(即 formatDate()
)映射 arra1
的每个项目,其中 .getDate()
, .getMonth()
和 .getYear()
用于填充格式化字符串:
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
这里需要考虑的一些要点是:
Date#getMonth()
returns 0-indexed dates在 0-11 范围内。要匹配所需的日期格式,您应该添加1
,如图所示- 检查小于
10
的日期和月份值并在前缀0
中填充这些数字以获得所需的格式
这可以添加到您现有的代码中,如下所示:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length,
temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
/* Update this line */
return arra1.map(formatDate);
}
console.log(shuffle(dateArr));
关于JavaScript:如何获得没有时区的简单日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57795619/