添加日期后缀

时间:2016-07-12 08:17:05

标签: javascript date suffix

我有以下Javascript来显示页面上的日期,但我想添加" th"," st"和" rd"每个日期编号后面的后缀(即" 6th")。

有没有办法使用我目前拥有的以下代码?

    <script language="Javascript">
<!-- 

// Array of day names
var dayNames = new Array("You're working today? It's Sunday","Hello, it's Monday","Hello, it's Tuesday","Hello, it's Wednesday",
    "Hello, it's Thursday","Hello, it's Friday","You're working today? It's Saturday");

// Array of month Names
var monthNames = new Array(
"January","February","March","April","May","June","July",
"August","September","October","November","December");

var now = new Date();
document.write (dayNames[now.getDay()] + ", " + 
now.getDate() + " " + 
monthNames[now.getMonth()] + " " + 
now.getFullYear() + ".");
// -->
</script>

提前致谢

2 个答案:

答案 0 :(得分:0)

如果您不想使用库,还有其他解决方案。快速搜索StackOverflow让我看到了answer。您需要将其中一个函数合并到代码中,并从now.getDate()中获取值。

答案 1 :(得分:0)

您正在使用dayNames[now.getDay()]表示您要搜索的密钥为now.getDay(),这不是从零开始的。我建议您在数组末尾移动星期日的值,并使用dayNames[now.getDay() - 1]以获得更清晰。

关于这个问题,您可以查看解决方案的答案: Convert date day (05/12/2011 to 12th)