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
Can be done with 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>
Using the Intl object (or via toLocaleString) is somewhat problematic, but it can be made precise using the formatToParts method and manually putting the parts in order, e.g.
function formatDate(date = new Date()) {
let {day, month, year} = new Intl.DateTimeFormat('en', {
day:'2-digit',
month: 'short',
year: 'numeric'
}).formatToParts(date).reduce((acc, part) => {
if (part.type != 'literal') {
acc[part.type] = part.value;
}
return acc;
}, Object.create(null));
return `${day}-${month}-${year}`;
}
console.log(formatDate());
Using reduce on the array returned by formatToParts trims out the literals and creates an object with named properties that is then assigned to variables and finally formatted.
This function doesn't always work nicely for languages other than English though as the short month name may have punctuation.
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
const date = new Date();
date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))
the DD-MM-YYYY is just one of the formats. The format of the jquery plugin, is based on this list: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Tested following code in chrome console:
test = new Date()
test.format('d-M-Y')
"15-Dec-2014"
var date = new Date();
console.log(date.toJSON().slice(0,10).replace(new RegExp("-", 'g'),"/" ).split("/").reverse().join("/")+" "+date.toJSON().slice(11,19));
// output : 01/09/2016 18:30:00