0

Please Help! I need to get my date format in 6th August 2020 but what I have with the code below is 6-8-2020.

// time and date
var today = new Date();

//var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var date = today.getDate() + '-' + (today.getMonth() + 1) + '-' + today.getFullYear();

var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var dateTime = date + ' ' + time;
document.getElementById("t1").innerHTML = dateTime;
<div id='t1'></div>
fedesc
  • 2,270
  • 2
  • 18
  • 34
  • Does this help? https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – Dirk R Aug 06 '20 at 14:09

4 Answers4

1

function formatDate(date) {
    const MONTH = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return date.getDate() +'th ' + MONTH[date.getMonth()] + ' ' + date.getFullYear();
 }

let date = new Date();
console.log ( formatDate(date));
Sascha
  • 4,416
  • 3
  • 11
  • 33
0

Your best bet is to use the moment library. You will need to install the package into your project but once you do you can do this with one line:

var today = moment().format("Do MMMM YYYY");

You can see how to install it here depending on the type of project you have: https://momentjs.com/docs/

Edit: you can also do the time as well in the same line:

var dateTime = moment().format("do MMMM YYYY hh:mm:ss");
Jacob P
  • 150
  • 5
0

This code will give you a closer result. I don't know where are you live in. However, this code is for the USA. If you wanna change it, just replace the country code.

const date = new Date().toLocaleString("en-US", {
  day: 'numeric',
  month: 'long',
  year: 'numeric',  
})

console.log(date)
cooskun
  • 196
  • 1
  • 11
0

Like @Jacob said, you could use some libraries like moment or date-fns.

Or go with something like this:

// time and date
var today = new Date();

const month = today.toLocaleString('default', { month: 'long' });

const ordinalDate = today.getDate() + ( [,'st','nd','rd'][/1?.$/.exec(today.getDate())] || 'th' );

var date = ordinalDate+'-'+month+'-'+today.getFullYear();

var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

var dateTime = date+' '+time;

console.log(dateTime);
Luis Paulo Pinto
  • 2,626
  • 9
  • 24