gpt4 book ai didi

javascript - 在 JavaScript/Jquery 中获取 DD-Mon-YYYY 格式的当前日期

转载 作者:行者123 更新时间:2023-12-03 21:29:58 25 4
gpt4 key购买 nike

我需要在 JavaScript 中获取日期格式为“DD-Mon-YYYY”。我问过question ,并且它被标记为重复到 jQuery date formatting

但是,问题中提供的答案是获取“DD-MM-YYYY”格式的当前日期,而不是“DD-MON-YYYY”格式。其次,我没有使用 datepicker 插件。

您能帮我看看如何获​​取“DD-Mon-YYYY”格式的当前日期吗?

最佳答案

JavaScript 中没有 DD-Mon-YYYY 的 native 格式。

您必须手动将它们组合在一起。

答案的灵感来自: How do I format a date in JavaScript?

// Attaching a new function  toShortFormat()  to any instance of Date() class

Date.prototype.toShortFormat = function() {

const monthNames = ["Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"];

const day = this.getDate();

const monthIndex = this.getMonth();
const monthName = monthNames[monthIndex];

const year = this.getFullYear();

return `${day}-${monthName}-${year}`;
}

// Now any Date object can be declared
let anyDate = new Date(1528578000000);

// and it can represent itself in the custom format defined above.
console.log(anyDate.toShortFormat()); // 10-Jun-2018

let today = new Date();
console.log(today.toShortFormat()); // today's date

关于javascript - 在 JavaScript/Jquery 中获取 DD-Mon-YYYY 格式的当前日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27480262/

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