让日期区间更友好!
把常见的日期格式如:YYYY-MM-DD 转换成一种更易读的格式。
易读格式应该是用月份名称代替月份数字,用序数词代替数字来表示天 (1st 代替 1).
记住不要显示那些可以被推测出来的信息: 如果一个日期区间里结束日期与开始日期相差小于一年,则结束日期就不用写年份了。月份开始和结束日期如果在同一个月,则结束日期月份就不用写了。
另外, 如果开始日期年份是当前年份,且结束日期与开始日期小于一年,则开始日期的年份也不用写。
code:
function makeFriendlyDates(arr) {
var date1={};var date2={};
var newArr=[];
for(var i=0;i<arr.length;i++){
newArr[i]=arr[i].split("-");
if(i === 0){
date1["year"]=newArr[i][0];
date1["month"]=newArr[i][1];
date1["day"]=newArr[i][2];
}else{
date2["year"]=newArr[i][0];
date2["month"]=newArr[i][1];
date2["day"]=newArr[i][2];
}
}//通过这段程序把两个日期参数转化为两个json对象。格式为{"year":xxxx,"month:xx","day":xxx}
var oMonth={
"01":"January",
"02":"February",
"03":"March",
"04":"April",
"05":"May",
"06":"June",
"07":"July",
"08":"August",
"09":"September",
"10":"October",
"11":"November",
"12":"December"
};
function getDay(obj){
switch(obj["day"]){
case "01":
obj["day"]="1st";
break;
case "02":
obj["day"]="2nd";
break;
case "03":
obj["day"]="3rd";
break;
case "04":
case "05":
case "06":
case "07":
case "08":
case "09":
obj["day"]=obj["day"][1]+"th";
break;
case "21":
obj["day"]+='st';
break;
case "22":
obj["day"]+='nd';
break;
case "23":
obj["day"]+='rd';
break;
default:
obj["day"]+='th';
}
for(i in oMonth){
if(obj["month"] == i){
obj["month"] = oMonth[i];
}
}
}
getDay(date1);
getDay(date2);
if(date1["year"]==date2["year"]){//是否同年
if(date1["month"]==date2["month"]){//是否同年同月
if(date1["day"]==date2["day"]){//是否同年同月同日
return [[date1["month"],date1["day"]+",",date1["year"]].join(' ')];
}else{//同年同月不同日
delete date1["year"];
delete date2["year"];
delete date2["month"];
}
}else{ //同年不同月
delete date2["year"];
}
}else if((Math.abs(date1["year"]-date2["year"])==1)){//不同年,年份但只差一年
if(date1["month"]<date2["month"]){//如果在一年以内
delete date1["year"];
delete date2["year"];
}else if(date1["month"]==date2["month"]){//差一年同月
if(date1["day"]>date2["day"]){ //小于一年
delete date2["year"];
}
}
}
function retArr(obj1,obj2){
var returnArr=[];
var objstr1=[obj1["month"],obj1["day"]+",",obj1["year"]].filter(function(a){return a!=undefined;}).join(' ');
var objstr2=[obj2["month"],obj2["day"]+",",obj2["year"]].filter(function(a){return a!=undefined;}).join(' ');
if(objstr1.substring(objstr1.length-1)==','){
objstr1=objstr1.replace(objstr1.substring(objstr1.length-1),'')
}
if(objstr2.substring(objstr2.length-1)==','){
console.log(objstr1.substring(objstr1.length-1))
objstr2=objstr2.replace(objstr2.substring(objstr2.length-1),'')
}
returnArr=[objstr1,objstr2];
return returnArr;
}
return retArr(date1,date2);
}
makeFriendlyDates(["2018-01-13", "2018-01-13"]);