60

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 provided in the question are to get the current date in "DD-MM-YYYY" format and not "DD-MON-YYYY". Secondly, I am not using datepicker plugin.

Can you please help me as if how to get the current date in "DD-Mon-YYYY" format.

1
  • The currently accepted answer is overly complicated. I've edited another answer that I think answers your question better. Can you please take a look? Commented Sep 27, 2018 at 0:57

18 Answers 18

86

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 do I format a date in JavaScript?

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

Date.prototype.toShortFormat = function() {

    const monthNames = ["Jan", "Feb", "Mar", "Apr",
                        "May", "Jun", "Jul", "Aug",
                        "Sep", "Oct", "Nov", "Dec"];
    
    const day = this.getDate();
    
    const monthIndex = this.getMonth();
    const monthName = monthNames[monthIndex];
    
    const 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

0
61

You can use toLocaleDateString and hunt for a format that's close to DD-mmm-YYYY (hint: 'en-GB'; you just need to replace the spaces with '-').

const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
  day: 'numeric', month: 'short', year: 'numeric'
}).replace(/ /g, '-');
console.log(formattedDate);

4
  • my output format is Dec-11,-2019 which is not expected. please help me out Commented Dec 11, 2019 at 10:25
  • @SujathaGirijala did you find a solution?
    – Amy Doxy
    Commented Apr 21, 2020 at 7:58
  • 1
    @SujathaGirijala that's probably because of the locale you're using. 'en-GB' is used in this example and that should give you DD Mon YYYY. If you use locale 'en-US' you get Mon DD, YYYY.
    – Calsal
    Commented Oct 28, 2020 at 13:49
  • Ugh, this returns "12-Sept-2023" for me today. I'm sorry for all the 56 people who upvoted this.
    – Nickolay
    Commented Sep 12, 2023 at 17:58
25

Use the Moment.js library http://momentjs.com/ It will save you a LOT of trouble.

moment().format('DD-MMM-YYYY');
4
  • 3
    It will also bloat your code a lot and is unnecessary when JavaScript core can solve the problem without libraries. Commented Sep 27, 2018 at 0:54
  • 1
    Well yes. There is also the excellent date-fns library date-fns.org. I mean with today's npm packages it hardly makes sense to roll your own. Commented Sep 27, 2018 at 11:13
  • There are a large number of date libraries, should there be an answer for every one of them? Many are much smaller than moment.js.
    – RobG
    Commented Apr 21, 2020 at 8:26
  • @RobG Indeed there are now, but back in 2014, when I gave this answer, there really wasn't much to play with. Commented Apr 21, 2020 at 8:29
15

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>

1
  • This gives "12-Sept-2023"
    – Nickolay
    Commented Sep 12, 2023 at 17:59
4

I've made a custom date string format function, you can use that.

var  getDateString = function(date, format) {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        getPaddedComp = function(comp) {
            return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
        },
        formattedDate = format,
        o = {
            "y+": date.getFullYear(), // year
            "M+": months[date.getMonth()], //month
            "d+": getPaddedComp(date.getDate()), //day
            "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
             "H+": getPaddedComp(date.getHours()), //hour
            "m+": getPaddedComp(date.getMinutes()), //minute
            "s+": getPaddedComp(date.getSeconds()), //second
            "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
            "b+": (date.getHours() >= 12) ? 'PM' : 'AM'
        };

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                formattedDate = formattedDate.replace(RegExp.$1, o[k]);
            }
        }
        return formattedDate;
    };

And now suppose you've :-

    var date = "2014-07-12 10:54:11";

So to format this date you write:-

var formattedDate = getDateString(new Date(date), "d-M-y")
2
3

By default, new Date().toString() will always return 'Sun Dec 12 2021...', so:

d=new Date();
s=d.getDate()+'-'+d.toString().substr(4,3)+'-'+d.getFullYear();

console.log(s);

No JQuery needed.

2
const date = new Date();

date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))
2
2

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.

1
  • The perfect answer! Rest all answers will produce the result in a different order
    – Sushin Pv
    Commented Apr 21, 2020 at 3:05
1

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"
5
  • yes I understand the date format, but how can I convert current date to dd-mon-yyyy, Eg I want to get current date in 15-Dec-2014, format.
    – Tushar
    Commented Dec 15, 2014 at 8:55
  • Normally this should work (tested in console): test = new Date(); test.format('d-M-Y')
    – Vince V.
    Commented Dec 15, 2014 at 8:59
  • 1
    agreed. this would be great but format is not a function Commented Aug 21, 2016 at 11:01
  • 6
    When executed in console TypeError: test.format is not a function test = new Date() test.format('d-M-Y');
    – Smile
    Commented Mar 27, 2017 at 10:10
  • 2
    this is JS not Java
    – Felix
    Commented Jan 18, 2018 at 4:19
1
/*
  #No parameters
  returns a date with this format DD-MM-YYYY
*/
function now()
{
  var d = new Date();
  var month = d.getMonth()+1;
  var day = d.getDate();

  var output = (day<10 ? '0' : '') + day + "-" 
              + (month<10 ? '0' : '') + month + '-'
              + d.getFullYear();

  return output;
}
1
  • This is a very low quality answer: please provide explanation of what your code does. Also, this code does not take parameter, but does expect a global variable d. Finally, it does not answer OPs question: YYYY/MM/DD is not the same as DD-Mon-YYY that was asked for.
    – wintvelt
    Commented May 14, 2016 at 20:27
1

Pass data changeFormate(15/07/2020)

  changeFormate(date) {
let month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let incomingDateChnge: any = new Date(date);
let incomingDay = incomingDateChnge.getDate();
let incomingMonth = incomingDateChnge.getMonth();

let incomingYear = incomingDateChnge.getFullYear();
if (incomingDay < 10) {
  incomingDay = '0' + incomingDay;
}

incomingDateChnge = incomingDay + ' ' + month_names[incomingMonth] + ' ' + incomingYear;
return incomingDateChnge;
 }
1

Here's a simple solution, using TypeScript:

  convertDateStringToDate(dateStr) {
    //  Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
    let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    let date = new Date(dateStr);
    let str = date.getDate()
                + '/' + months[date.getMonth()]
                + '/' + date.getFullYear()
    return str;
  }

(Yeah, I know the question was about JavaScript, but I'm sure I won't be the only Angular developer coming across this article !)

1

const date = new Date();
const formattedDate = date.toLocaleDateString('en-GB', {
  day: 'numeric', month: 'short', year: 'numeric'
});
console.log(formattedDate);

2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 5, 2022 at 7:36
  • 1
    OP wanted DD-Mon-YYYY, your answer is DD/MM/YYYY. Commented Jan 6, 2022 at 20:40
0

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var currDate= new Date();
var newDate=currDate.toLocaleDateString();
var splitNewDate= newDate.split('/');
var formatDate= splitNewDate[1] + '-'+ monthNames[splitNewDate[0]] +'-'+ splitNewDate[2];

console.log(formatDate);

//convert DateTime result in jquery mvc 5 using entity fremwork 

const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    

function DateAndTime(date) {
 
    var value = new Date
        (
        parseInt(date.replace(/(^.*\()|([+-].*$)/g, ''))
    ); 
    var dat = value.getDate() +
        "-" +
        monthNames[value.getMonth()] +
        "-" +
        value.getFullYear();

    var hours = value.getHours();
    var minutes = value.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return { Date: dat, Time: strTime };
}
// var getdate = DateAndTime(StartDate);
//var Date = getdate.Date;//here get date
//var time = getdate.Time;//here get Time
//alert(Date)
0

Try this.

function dateFormat(D) {
  const monthNames = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];

  const day = D.getDate();

  const monthIndex = D.getMonth();
  const monthName = monthNames[monthIndex];

  const year = D.getFullYear();

  return `${day}-${monthName}-${year}`;
}

// Write Javascript code!
const appDiv = document.getElementById('app');
appDiv.innerHTML = `<h1>JS ${dateFormat(new Date('2023-07-05'))}</h1>`;
<div id="app"></div>

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

0
-2

            var today = new Date();           

            var formattedtoday = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();
            
            alert(formattedtoday);

1
  • This answer does not meet the requirement of the OP. The required format is dd-Mon-yyyy not dd-MM-yyyy
    – Ahmad
    Commented Oct 22, 2017 at 10:54
-7

Use date format dd-MM-yy . It will output like: 16-December-2014.

1
  • 1
    This is not an answer. Please post a valid applicable answer
    – Ahmad
    Commented Dec 15, 2014 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.