Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
–1 vote
2 views
in Java by (13.1k points)
Can anyone help me how I can able to change the date format 'DD-Mon-YYYY', but everywhere it shows 'DD-MM-YYYY'. Can anyone help me with this?

1 Answer

0 votes
by (26.7k points)

Basically, there is no format present in javascript for DD-Mon-YYYY. You have to do it manually.

// 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

I hope this will help.

Want to become a Java expert? join Java Training now!!

Related questions

0 votes
1 answer
asked Jan 28, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...