ex15-10-2
実行結果
0. 2019年10月15日
1. 2018年5月13日
2. 2019年12月5日
3. 2019年4月7日
4. 2017年3月20日
5. 2017年4月6日
6. 2017年5月21日
7. 2019年11月15日
8. 2018年10月28日
9. 2018年11月28日
----
0. 2019年12月5日
1. 2019年11月15日
2. 2019年10月15日
3. 2019年4月7日
4. 2018年11月28日
5. 2018年10月28日
6. 2018年5月13日
7. 2017年5月21日
8. 2017年4月6日
9. 2017年3月20日
----
0. 2017年3月20日
1. 2017年4月6日
2. 2017年5月21日
3. 2018年5月13日
4. 2018年10月28日
5. 2018年11月28日
6. 2019年4月7日
7. 2019年10月15日
8. 2019年11月15日
9. 2019年12月5日
ソース
const dates = [];
const min = new Date(2017, 0, 1).valueOf();
const delta = new Date(2020, 0, 1).valueOf() - min; /* 差 */
/* 2017年1月1日から2020年1月1日の間の日時をランダムに生成して、datesに記憶 */
for(let i=0; i<10; i++)
dates.push(new Date(min + delta*Math.random()));
printDates(dates);
console.log("----");
dates.sort((a, b) => b - a); /* 降順にソート*/
printDates(dates);
console.log("----");
dates.sort((a, b) => a - b); /* 昇順にソート*/
printDates(dates);
function printDates(dates) {
for(let i=0; i<dates.length; i++) {
const d = dates[i];
console.log(i + ". " + d.getFullYear()+"年"+(d.getMonth()+1)+"月"
+d.getDate()+"日");
}
}