我需要在javascript中获取日期格式为'DD-Mon-YYYY‘。我问过一个question,它被标记为jQuery date formatting的副本
但是,问题中提供的答案是以"DD-MM-YYYY“格式获取当前日期,而不是"DD-MON-YYYY”。其次,我没有使用datepicker插件。
你能告诉我如何获取"DD-Mon-YYYY“格式的当前日期吗?
发布于 2014-12-15 16:54:45
javascript中没有用于DD-Mon-YYYY
的本机格式。
您将不得不手动将它们组合在一起。
答案的灵感来自:How to format a JavaScript date
// Attaching a new function toShortFormat() to any instance of Date() class
Date.prototype.toShortFormat = function() {
let monthNames =["Jan","Feb","Mar","Apr",
"May","Jun","Jul","Aug",
"Sep", "Oct","Nov","Dec"];
let day = this.getDate();
let monthIndex = this.getMonth();
let monthName = monthNames[monthIndex];
let 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
发布于 2014-12-15 17:09:21
您可以使用toLocaleDateString并寻找一种接近DD-mmm YYYY的格式(提示:'en-GB';您只需将空格替换为'-')。
const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
day: 'numeric', month: 'short', year: 'numeric'
}).replace(/ /g, '-');
console.log(formattedDate);
发布于 2014-12-15 16:54:35
使用Moment.js库http://momentjs.com/,它将为您省去很多麻烦。
moment().format('DD-MMM-YYYY');
https://stackoverflow.com/questions/27480262
复制相似问题