在JavaScript/Jquery中以DD-Mon-YYY格式获取当前日期

Tus*_*har 27 javascript jquery datetime date

我需要在javascript中将日期格式设为'DD-Mon-YYYY'.我问了一个问题,它被标记为jQuery日期格式的副本

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

你能帮助我,好像如何以"DD-Mon-YYYY"格式获取当前日期.

Ahm*_*mad 55

javascript中没有原生格式DD-Mon-YYYY.

您必须手动将它们全部放在一起.

答案的灵感来自: 如何格式化JavaScript日期

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

Date.prototype.toShortFormat = function() {

    var month_names =["Jan","Feb","Mar",
                      "Apr","May","Jun",
                      "Jul","Aug","Sep",
                      "Oct","Nov","Dec"];
    
    var day = this.getDate();
    var month_index = this.getMonth();
    var year = this.getFullYear();
    
    return "" + day + "-" + month_names[month_index] + "-" + year;
}

// Now any Date object can be declared 
var today = new Date();


// and it can represent itself in the custom format defined above.
console.log(today.toShortFormat());    // 10-Jun-2018
Run Code Online (Sandbox Code Playgroud)


tec*_*use 19

使用Moment.js库http://momentjs.com/这将为您省去很多麻烦.

moment().format('DD-MMM-YYYY');
Run Code Online (Sandbox Code Playgroud)

  • 它还会[让你的代码变得很多](https://github.com/moment/moment/issues/3376),并且当[JavaScript核心可以在没有库的情况下解决问题](https://stackoverflow.com/ a/27480577/1269037)。 (3认同)

Jer*_*ony 14

您可以使用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);
Run Code Online (Sandbox Code Playgroud)


Yan*_*nga 12

可以用 toLocaleDateString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

<script>
const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
  day: '2-digit', month: 'short', year: 'numeric'
}).replace(/ /g, '-');
document.write(formattedDate);
</script>
Run Code Online (Sandbox Code Playgroud)