1. 程式人生 > >W3Cschool高階指令碼演算法(6.日期改寫演算法挑戰)

W3Cschool高階指令碼演算法(6.日期改寫演算法挑戰)

日期改寫演算法挑戰

問題:

讓日期區間更友好!

把常見的日期格式如: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"].

要求:

makeFriendlyDates(["2016-07-01", "2016-07-04"]) should return ["July 1st, 2016","4th"].

makeFriendlyDates(["2016-12-01", "2017-02-03"]) should return ["December 1st, 2016","February 3rd"].

makeFriendlyDates(["2016-12-01", "2018-02-03"])

should return ["December 1st, 2016","February 3rd, 2018"].

makeFriendlyDates(["2017-03-01", "2017-05-05"]) should return ["March 1st, 2017","May 5th"]

makeFriendlyDates(["2018-01-13", "2018-01-13"]) should return ["January 13th, 2018"].

makeFriendlyDates(["2022-09-05", "2023-09-04"]) should return ["September 5th, 2022","September 4th"]

.

makeFriendlyDates(["2022-09-05", "2023-09-05"]) should return ["September 5th, 2022","September 5th, 2023"].

問題答案:

function makeFriendlyDates(arr) {
    var fArr = arr[0].split('-'),
        tArr = arr[1].split('-'),
        fY = fArr[0],
        fM = fArr[1],
        fD = fArr[2],
        tY = tArr[0],
        tM = tArr[1],
        tD = tArr[2],
        mArr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        dArr = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th', '11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th', '31st'], 
        today = new Date(),
        rArr=[];
    if (arr[0] === arr[1]) {
        rArr[0] = mArr[parseInt(fM) - 1] + ' ' + dArr[parseInt(fD) - 1] + ', ' + fY;
        return rArr;
    }
    if ((new Date(parseInt(tY), parseInt(tM) - 1, parseInt(tD))).getTime() - (new Date(parseInt(fY), parseInt(fM) - 1, parseInt(fD))).getTime() < 3600000 * 24 * 365)
    {
        var year = today.getFullYear();
        if (parseInt(fY) === year) {
            rArr[0] = mArr[parseInt(fM) - 1] + ' ' + dArr[parseInt(fD) - 1];
        } else {
            rArr[0] = mArr[parseInt(fM) - 1] + ' ' + dArr[parseInt(fD) - 1] + ', ' + fY;
        }
        if (tM === fM && tY===fY) {
            rArr[1] = dArr[parseInt(tD) - 1];
        } else {
            rArr[1] = mArr[parseInt(tM) - 1] + ' ' + dArr[parseInt(tD) - 1];
        }
    } else {
        rArr[0] = mArr[parseInt(fM) - 1] + ' ' + dArr[parseInt(fD) - 1] + ', ' + fY;
        rArr[1] = mArr[parseInt(tM) - 1] + ' ' + dArr[parseInt(tD) - 1] + ', ' + tY;
    }
    return rArr;
}


makeFriendlyDates(['2017-03-01', '2017-05-05']);

題目連結: