-1

I have found examples for displaying date but I need it in a specific format, ie: 15 Jun 2018, but the months are shortened

[Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]

So need it to display todays date in the above format.

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

function dateFormat2(d) {
  var t = new Date(d);
  return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear();
}

//console.log(dateFormat2(new Date()))
var showDate = dateFormat2(new Date())

document.getElementById("todays-date").innerHTML = showDate + 14:44;

Then trying to output it in a div here:

<div id="todays-date"></div>

Can't seem to get it working. If there's a better way please let me know. Thanks

isherwood
  • 46,000
  • 15
  • 100
  • 132
John
  • 1,737
  • 8
  • 37
  • 61

3 Answers3

0


I converted the code to a string, then split it by spaces. From there I was able to splice the array as needed.

function dateFormat2(d) {
  var date = d.toString().split(" ");
  return `${date.splice(1, 2).reverse().join(" ")} ${date[1]}`;
}
var showDate = dateFormat2(new Date());
document.getElementById("todays-date").innerHTML = showDate;
<div id="todays-date"></div>
Sarah
  • 390
  • 2
  • 9
0

Here is the full working example

<p id="demo"></p>

<script>
    var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];

    function getTime(t) {
        let hours = t.getHours(); 
        if(hours.toString().length == 1) {
            hours = "0" + hours;
        }
        let minutes = t.getMinutes(); 
        if(minutes.toString().length == 1) {
            minutes = "0" + minutes;
        }
        return hours + ':' + minutes;
    }
    function dateFormat2() {
        var t = new Date();
        return t.getDate() + ' ' + monthShortNames[t.getMonth()] + ', ' + t.getFullYear() + ' ' + getTime(t);
    }
    document.getElementById("demo").innerHTML = dateFormat2();

click here for working demo

Gohel Dhaval
  • 750
  • 1
  • 7
  • 12
-1

It wasn't printing out the date, needed this:

document.getElementById("todays-date").innerHTML = (dateFormat2(new Date()));
John
  • 1,737
  • 8
  • 37
  • 61