Google Scripts中日期序数格式转换方法(th、rd、st、nd)
I’ve been scouring for a simple function to turn dates (specifically ones from Google Form submissions) into the ordinal format used in contracts—like 25th day of May, 2018. I saw someone asked this exact question before, but it got marked as a duplicate, and the linked answers didn’t actually solve the problem.
So I put together a straightforward function that gets the job done:
function ordinal(date) { var d = date.getDate(); var month = new Array (); month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April"; month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August"; month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December"; var m = month[date.getMonth()]; var y = date.getYear(); return d + (d > 0 ? ['th', 'st', 'nd', 'rd'][(d > 3 && d < 21) || d % 10 > 3 ? 0 : d % 10] : '') + " day of " + m +", " + y; }
It takes a Date object as input, extracts the day, full spelled-out month, and year, then appends the correct ordinal suffix (st/nd/rd/th). It even handles tricky edge cases like 11th, 12th, 13th—those don’t follow the usual suffix rules, and this function accounts for that!
内容的提问来源于stack exchange,提问作者Mindy Zwanziger

