我的数组充满了日期。我想从这个数组中获得3个单独的信息。
示例数组日期:
"02/11/2019 11:22:28",
"05/14/2019 12:17:49",
"06/06/2019 09:00:00",
"05/02/2019 11:05:30"
我相信moment.js可以在这里提供帮助,但是我无法使其正常工作。
答案 0 :(得分:0)
我认为您不需要导入JS框架即可完成
。您可以在普通JavaScript中比较Dates
。
const arrayOfDates = ["02/11/2019 11:22:28", "02/11/2020 11:22:28",
"04/03/2019 11:33:54"];
const TODAY = new Date();
const END_OF_TODAY = new Date(TODAY.getFullYear(), TODAY.getMonth(), TODAY.getDay(), 24, 59, 59);
const END_OF_TOMORROW = new Date(TODAY.getFullYear(), TODAY.getMonth(), TODAY.getDay() + 1, 24, 59, 59);
let datesBeforeToday = [];
let datesBetweenNowAndEndOfDate = [];
let datesWithTomorrowsDate = [];
for (var i=0; i<arrayOfDates.length; i++)
{
var dateInArray = new Date(arrayOfDates[i]);
// Before today
if (TODAY > dateInArray)
{
datesBeforeToday.push(dateInArray);
}
// between now - end of today
else if (END_OF_TODAY >= dateInArray)
{
datesBetweenNowAndEndOfDate.push(dateInArray);
}
// between end of today - end of tomorrow
else if (END_OF_TOMORROW >= dateInArray)
{
datesWithTomorrowsDate.push(dateInArray);
}
}
// 1) Number of dates before 'now'
console.log(datesBeforeToday.length);
// 2) Number of dates between 'now' and the end of the current date
console.log(datesBetweenNowAndEndOfDate.length);
// 3) Number of dates with tomorrow date
console.log(datesWithTomorrowsDate.length);
答案 1 :(得分:0)
这是不使用moment.js的一种方法:
var dates = [
"11/02/2018 11:22:28",
"02/02/2019 11:22:28",
"04/04/2019 11:22:28",
"10/03/2019 11:22:28",
"11/02/2019 11:22:28"
];
var res = { before: 0, tomorrow: 0, after: 0 }
var tomorrow00 = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
tomorrow00.setHours(0, 0, 0, 0);
var tomorrow24 = new Date(new Date().getTime() + 48 * 60 * 60 * 1000);
tomorrow24.setHours(0, 0, 0, 0);
tomorrow24.setTime(tomorrow24.getTime() - 1)
dates.forEach((date)=>{
var current = new Date(date);
if ((current >= tomorrow00) && (current <= tomorrow24))
res.tomorrow++;
else if (current < Date.now())
res.before++;
else if (current > Date.now())
res.after++
})
console.log(res);
这是解决使用moment.js的一种方法
var dates = [
"11/02/2018 11:22:28",
"02/02/2019 11:22:28",
"04/04/2019 11:22:28",
"10/03/2019 11:22:28",
"11/02/2019 11:22:28"
];
var res = { before: 0, tomorrow: 0, after: 0 };
const tomorrow00 = moment().add(1, 'day').startOf('day');
const tomorrow24 = moment().add(1, 'day').endOf('day');
dates.forEach((date)=>{
var current = moment(date, "MM/DD/YYYY HH:mm:ss");
if ((current.isAfter(tomorrow00)) && (current.isBefore(tomorrow24)) )
res.tomorrow++;
else if (current.isBefore(moment().startOf('day')))
res.before++;
else if (current.isAfter(moment().endOf('day')))
res.after++
})
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>