Alison
Alison

Reputation: 249

How to get the full date with javascript?

I am trying to get the full date with my function. Right now my results are "Wed Feb 14 2018", but I would like it to say "Wednesday February 2018". I want it to say the whole day and whole month. I could not find a "get fullDate" method unfortunately..

window.onload = function() {
  var date = new Date();

  document.getElementById("date").innerHTML = date.toDateString();
}
<div id="date"> </div>

Upvotes: 3

Views: 1084

Answers (3)

Jason Cust
Jason Cust

Reputation: 10899

As you have noticed, the native Date methods are a bit limited. There are a handful of roll-your-own approaches and if this is all you need then that is probably what you should use. If you need something more robust I would recommend a library to avoid running over many pitfalls in attempting to handle the craziness of formatting time correctly.

A very popular library is called momentjs. A very simple solution for your issue is to use their format method:

const date = new Date();

document.getElementById("date").innerHTML = moment().format("dddd MMMM YYYY");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<div id="date"> </div>

Hope this helps!

Upvotes: 0

Sahin Erbay
Sahin Erbay

Reputation: 1014

If you are looking for native date methods:

function dateConvert(){
      let date = new Date();
      let year = date.getFullYear();
      let month= date.getMonth();
      let day = date.getDay();
  
      let months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
      let days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
  
      return converted_date = `${days[day]} ${months[month]}  ${year}`;
    }
    
document.write(dateConvert());

Upvotes: 0

John Pavek
John Pavek

Reputation: 2665

You're actually looking for the toLocaleString function, as it can be customized pretty heavily without losing your date object.

window.onload = function() {
  var date = new Date();

  document.getElementById("date").innerHTML = date.toLocaleString('en-US', {weekday: 'long', month: 'long', year: 'numeric'});
}
<div id="date"> </div>

Upvotes: 8

Related Questions