Shubham Khatri Shubham Khatri - 1 month ago 10
Javascript Question

Get Date/Timestamp in a particular format

I want to get Date in the for following format

16-SEP-16 12.00
in javascript. I can't quite figure out how to achieve this. I need to send this as a query parameter for a REST API request.

Currently all I can think of this to format the date individually like



var date = new Date();
var dt = date.getUTCDate() + '-' + date.getUTCMonth() + '-' + (date.getUTCFullYear() - 2000) + ' ' + date.getUTCHours() + '.' + date.getUTCMinutes();
console.log(dt);





I have a problem with it that the month is a number and not a shorthand like
SEP
.

Also is there any simple way to achieve this.

Thanks for help in advance.

Answer

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


var date = new Date();
var dt = date.getUTCDate() + '-' + monthNames[date.getUTCMonth()] + '-' + (date.getUTCFullYear() - 2000) + ' ' + date.getUTCHours() + '.' + date.getUTCMinutes();
console.log(dt);

without using month array you can use below solution

var date = new Date();
Date.prototype.monthName = function() {
    return this.toUTCString().split(' ')[2]
};
var dt = date.getUTCDate() + '-' + date.monthName()+ '-' + (date.getUTCFullYear() - 2000) + ' ' + date.getUTCHours() + '.' + date.getUTCMinutes();
console.log(dt);
document.write(dt);

Comments