Oluwafemi Akinyemi
Oluwafemi Akinyemi

Reputation: 119

Date and Time Format In JavaScript

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>

Upvotes: 0

Views: 190

Answers (4)

Sascha A.
Sascha A.

Reputation: 4616

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

Upvotes: 1

Luis Paulo Pinto
Luis Paulo Pinto

Reputation: 6036

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

Upvotes: 0

cooskun
cooskun

Reputation: 678

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)

Upvotes: 0

Jacob P
Jacob P

Reputation: 148

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

Upvotes: 0

Related Questions