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

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.

This question is related to javascript jquery date datetime

The answer is


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

moment().format('DD-MMM-YYYY');

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"

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


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 !)


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


const date = new Date();

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

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 '-').

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


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")

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;
 }

/*
  #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;
}

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


Can be done with toLocaleDateString

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

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


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

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.

_x000D_
_x000D_
function formatDate(date = new Date()) {_x000D_
  let {day, month, year} = new Intl.DateTimeFormat('en', {_x000D_
    day:'2-digit',_x000D_
    month: 'short',_x000D_
    year: 'numeric'_x000D_
  }).formatToParts(date).reduce((acc, part) => {_x000D_
    if (part.type != 'literal') {_x000D_
      acc[part.type] = part.value;_x000D_
    }_x000D_
    return acc;_x000D_
  }, Object.create(null));_x000D_
  return `${day}-${month}-${year}`;_x000D_
}_x000D_
_x000D_
console.log(formatDate());
_x000D_
_x000D_
_x000D_

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?