让日期区间更友好!
把常见的日期格式如:YYYY-MM-DD
转换成一种更易读的格式。
易读格式应该是用月份名称代替月份数字,用序数词代替数字来表示天 (1st
代替 1
).
记住不要显示那些可以被推测出来的信息: 如果一个日期区间里结束日期与开始日期相差小于一年,则结束日期就不用写年份了。月份开始和结束日期如果在同一个月,则结束日期月份就不用写了。
另外, 如果开始日期年份是当前年份,且结束日期与开始日期小于一年,则开始日期的年份也不用写。
例如:
makeFriendlyDates(["2016-07-01", "2016-07-04"])
应该返回 ["July 1st, 2016","4th"]
makeFriendlyDates(["2016-07-01", "2018-07-04"])
应该返回 ["July 1st, 2016", "July 4th, 2018"]
.
// 简单模拟
function makeFriendlyDates(arr) {
var month = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var dayth = ["st", "nd", "rd", "th"];
var ans = [];
var date1 = arr[0].split("-");
var date2 = arr[1].split("-");
var year1 &#61; (Number(date1[0]) &#61;&#61; 2017 && ((new Date(arr[1]) - new Date(arr[0])) / 1000 / 3600 / 24 <365)) ? "" : (", " &#43; date1[0]);
var month1 &#61; month[Number(date1[1]) - 1] &#43; " ";
var day1 &#61; Number(date1[2]) <&#61; 3 ? (parseInt(date1[2]) &#43; dayth[date1[2] - 1]) : (parseInt(date1[2]) &#43; dayth[3]);
var ans1 &#61; month1 &#43; day1 &#43; year1;
if(new Date(arr[1]).valueOf() &#61;&#61; new Date(arr[0]).valueOf() ) {
ans1 &#61; month1 &#43; day1 &#43; ", " &#43; date1[0]
return [ans1];
}
var year2 &#61; (((new Date(arr[1]) - new Date(arr[0])) / 1000 / 3600 / 24 <365)) ? "" : (", " &#43; date2[0]);
var month2 &#61; ((Number(date1[0]) &#61;&#61; Number(date2[0])) && (Number(date1[1]) &#61;&#61; Number(date2[1]))) ? "" : month[Number(date2[1]) - 1] &#43; " ";
var day2 &#61; Number(date2[2]) <&#61; 3 ? (parseInt(date2[2]) &#43; dayth[date2[2] - 1]) : (parseInt(date2[2]) &#43; dayth[3]);
var ans2 &#61; month2 &#43; day2 &#43; year2;
return [ans1, ans2];
}
makeFriendlyDates(["2018-01-13", "2018-01-13"])