Get current date in DD-Mon-YYY format in JavaScript/Jquery

后端 未结 15 1728
攒了一身酷
攒了一身酷 2020-12-01 03:06

I need to get the date format as \'DD-Mon-YYYY\' in javascript. I had asked a question, and it got marked duplicate to jQuery date formatting

But, the answers provi

15条回答
  •  再見小時候
    2020-12-01 03:32

    There is no native format in javascript for DD-Mon-YYYY.

    You will have to put it all together manually.

    The answer is inspired from : 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

提交回复
热议问题