Created
December 5, 2018 06:34
-
-
Save yuanoook/6ac81cfb79a3ad9dbe317051004dcfdd to your computer and use it in GitHub Desktop.
autoTypingZHDate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test(); | |
function check(bool) { | |
console.log(bool ? 'pass' : 'failed') | |
} | |
function test() { | |
check(autoTypingZHDate("201") === "201"); | |
check(autoTypingZHDate("2018") === "2018年"); | |
check(autoTypingZHDate("20181") === "2018年1"); | |
check(autoTypingZHDate("20189") === "2018年9月"); | |
check(autoTypingZHDate("208408") === "2084年08月"); | |
check(autoTypingZHDate("201819") === "2018年1月9日"); | |
check(autoTypingZHDate("2084812") === "2084年8月12日"); | |
check(autoTypingZHDate("208483") === "2084年8月3"); | |
check(autoTypingZHDate("2084083") === "2084年08月3"); | |
check(autoTypingZHDate("208484") === "2084年8月4日"); | |
check(autoTypingZHDate("2084084") === "2084年08月4日"); | |
check(autoTypingZHDate("2084081") === "2084年08月1"); | |
check(autoTypingZHDate("20840812") === "2084年08月12日"); | |
check(autoTypingZHDate("2084122") === "2084年12月2"); | |
check(autoTypingZHDate("20841222") === "2084年12月22日"); | |
} | |
function autoTypingZHDate(text) { | |
var numbersInText = text.replace(/\D/g, '').replace(/^0*/, '').split(''); | |
var year = numbersInText.splice(0, 4); | |
var month = numbersInText.splice(0, 1); | |
var day = numbersInText.splice(0, 3); | |
if ( | |
(month[0] === '1' && (/0|1|2/.test(day[0]))) | |
|| (month[0] === '0' && day.length) | |
) { | |
month.push(day.shift()); | |
} | |
if (year.length < 4) { | |
return year.join('') | |
} | |
if(!month.length) { | |
return year.join('') + '年' | |
} | |
if(month.length === 1 && month[0] < 2 && !day.length) { | |
return year.join('') + '年' + month.join('') | |
} | |
if (!day.length) { | |
return year.join('') + '年' + month.join('') + '月' | |
} | |
if (day.length < 2 && day[0] < 4) { | |
return year.join('') + '年' + month.join('') + '月' + day.join('') | |
} | |
return year.join('') + '年' + month.join('') + '月' + day.join('').substr(0, 2) + '日' | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment