Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Current date to div classname display 123 in year and wrong day

I am building my first javascript because I searched here and on many sites for a solution but could not find anyone for my case.

What I need is to display the current day value to a div with a classname and with day name and month name (customized). But the div is displaying the current date like this: Sat 6 Jun 123 so the year is wrong and the day name is wrong too

var  months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var today = new Date();
var day   = today.getDate();
var month = today.getMonth();
var year  = today.getYear();
var dia = today.getDay();
var display =  days[day] + " " + day + " " + months[month] + " " + year;
$('.first-date').html(display);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="first-date"></span>

Any idea why is this happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I did everything I could but I am new to Javascript/Jquery

>Solution :

getYear is now deprecated so you need to use getFullYear like:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var today = new Date();
var day = today.getDate();
var dayForText = today.getDay();
var month = today.getMonth();
var year = today.getFullYear();
var dia = today.getDay();
var display = days[dayForText] + " " + day + " " + months[month] + " " + year;
$('.first-date').html(display);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="first-date"></span>

And another error, getDay return number range 0-6 (for your array) not the actually number of day, so you need to create two variable one for you custom day and one for number of day

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading