gpt4 book ai didi

javascript - 如何在自定义JQuery中添加日期原始/后缀?

转载 作者:行者123 更新时间:2023-12-02 20:56:20 26 4
gpt4 key购买 nike

我有以下旨在修改日期格式的Javascript,但是我想添加原始日期或后缀,例如“st”,“nd”,“rd”,“th”到每个结束日期编号。例如,假设我们当前的日期设置为 4 月 28 日,但我想将日期显示为 4 月 28 日

因此,如果有可能...您如何将此示例编码添加到当前的 javascript 字符串中?

var 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"; } }

当前 JS:

  // Blog date
window.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.waddons-blog-meta').forEach(el => el.textContent = formatDateString(el.textContent))
}, false);
function formatDateString(s) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var arr = s.split('/');
return arr[1] + " " + months[arr[0] - 1];

}

当前 HTML:

<div class="waddons-blog-meta">3/7/2020 - </div>

最佳答案

您只需在代码中调用nth 函数即可。

var 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";
}
}

window.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.waddons-blog-meta').forEach(el => el.textContent = formatDateString(el.textContent))
}, false);
function formatDateString(s) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var arr = s.split('/');
return arr[1] + nth(arr[1]) + " " + months[arr[0] - 1];
}

如果您想为第 th 值添加上标,请使用以下代码

window.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.waddons-blog-meta').forEach(el => el.innerHTML = formatDateString(el.textContent))
}, false);
function formatDateString(s) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var arr = s.split('/');
return arr[1] + "<sup>" + nth(arr[1]) + "</sup>" + " " + months[arr[0] - 1];
}

关于javascript - 如何在自定义JQuery中添加日期原始/后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61474907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com