JavaScript 新日期序数(st、nd、rd、th) [英] JavaScript new Date Ordinal (st, nd, rd, th)
本文介绍了JavaScript 新日期序数(st、nd、rd、th)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果可能的话,没有 JavaScript 库或大量笨重的代码,我正在寻找一种最简单的方法来格式化两周后的日期,格式如下:
If at all possible, without JavaScript libraries or lots of clunky code I am looking for the simplest way to format a date two weeks from now in the following format:
2013 年 3 月 13 日
我使用的代码是:
var newdate = new Date(+new Date + 12096e5);
document.body.innerHTML = newdate;
返回两周后的日期和时间,但像这样:2013 年 3 月 27 日星期三 21:50:29 GMT+0000(GMT 标准时间)
which returns the date and time two weeks from now, but like this: Wed Mar 27 2013 21:50:29 GMT+0000 (GMT Standard Time)
这是jsFiddle中的代码.
任何帮助将不胜感激!
推荐答案
这里:
const nth = function(d) {
if (d > 3 && d < 21) return 'th';
switch (d % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
const fortnightAway = new Date(+new Date + 12096e5);
const date = fortnightAway.getDate();
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][fortnightAway.getMonth()];
document.getElementById("date").innerHTML = `In two weeks it will be the ${date}<sup>${nth(date)}</sup> ${month} ${fortnightAway.getFullYear()}`;
// test
const dates = [...Array(32).keys()].slice(1).map(i => `${i}${nth(i)}`)
console.log(dates.join(", "))
sup {
font-size: x-small
}
<span id="date"></span>
这篇关于JavaScript 新日期序数(st、nd、rd、th)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文