Call date by javascript

Asked

Viewed 113 times

-2

I am putting the date on the site with this code that is working, but this script has to be inside the HTML element in which the date will appear.

How can I change this script so that the date appears on a DIV identified by your ID?

var now = new Date();
var mName = now.getMonth() +1 ;
var dName = now.getDay() +1;
var dayNr = now.getDate();
var yearNr=now.getYear();
if(dName==1) {Day = "Domingo";}
if(dName==2) {Day = "Segunda-feira";}
if(dName==3) {Day = "Terça-feira";}
if(dName==4) {Day = "Quarta-feira";}
if(dName==5) {Day = "Quinta-feira";}
if(dName==6) {Day = "Sexta-feira";}
if(dName==7) {Day = "Sábado";}
if(mName==1){Month = "Janeiro";}
if(mName==2){Month = "Fevereiro";}
if(mName==3){Month = "Março";}
if(mName==4){Month = "Abril";}
if(mName==5){Month = "Maio";}
if(mName==6){Month = "Junho";}
if(mName==7){Month = "Julho";}
if(mName==8){Month = "Agosto";}
if(mName==9){Month = "Setembro";}
if(mName==10){Month = "Outubro";}
if(mName==11){Month = "Novembro";}
if(mName==12){Month = "Dezembro";}
if(yearNr < 2000) {Year = 1900 + yearNr;}
else {Year = yearNr;}
var todaysDate =(" " + "São Paulo, " + dayNr + " de " + Month + " de " + Year  +  " - " + Day  );

document.write('   '+todaysDate);
<!DOCTYPE html>
<html>

<body>
<!-- A data entraria nesta DIV -->
<div id="todaysDate">"  "</div>

</body>
</html>

  • 2

    Already tried something like at the end of the code, Document.getElementById('todaysDate'). innerHTML = todaysDate

  • 2

    Possible duplicate of Help with innerHTML in Javascript

  • Thanks for the help Henriquuepedro and Darlei Fernando Zilmer, I’ve changed here and it’s ok

3 answers

5

Inserting content into the DOM:

To insert any text into the DOM, you can make use of techniques such as textContent, append, and others. Since we only want to insert a text with the current date formatted, I will use the textContent.

You can do it like this:

// Selecionamos o elemento:
const element = document.querySelector('#el')

// Inserimos qualquer texto:
element.textContent = 'Olá, mundo!'
<div id="el"></div>


Regarding how to generate the string date formatted:

An interesting way to do this without creating this huge amount of ifs, which make the code extremely polluted is to use arrays:

// Criamos a instância da data:
const date = new Date()

// Capturamos o dia do mês e o ano:
const day = date.getDate()
const year = date.getFullYear()

// Capturamos o dia da semana:
const weekDayList = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado']
const weekDayString = weekDayList[date.getDay()]

// Capturamos o mês:
const monthList = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
const monthString = monthList[date.getMonth()]

// Criamos a string final:
const dateString = `São Paulo, ${day} de ${monthString} de ${year} - ${weekDayString}`

// Inserimos a data na `div#date`:
document.querySelector('#date').textContent = dateString
<div id="date"></div>

Explanation:

Bearing in mind that the methods getDay and getMonth return a value with zero index, we can create a list mapping the number returned by these methods to its corresponding name.

Example:

If getDay return 3, taking into account that the getDay returns the day of the week with index zero, we could conclude that this would correspond to "Wednesday", since:

  • 0 Domingo;
  • 1 Monday;
  • 2 Tuesday;
  • 3 Wednesday;
  • Other days of the week...

See working:

const weekDayList = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado']

// Asumindo que `date.getDay` retorne 3:
const returnValue = 3

// O output abaixo deve mostrar "Quarta-feira":
console.log(returnValue, '⇒', weekDayList[returnValue])

And that same behavior holds true for getMonth, which returns the month of the year with index from zero.


In short, Javascript is an extremely powerful language that allows you to do amazing things. This is an example of how language flexibility can help you simplify code. This is making it easier!! :)

3

If you already use pure javascript, there is no need to use Jquery, note that there is no need to use the global window object in onload, usually people use window.onload because they do not know that they can work without the window.

follows an example:

<html>

<script>
onload = function(){
  var now = new Date();
  var mName = now.getMonth() +1 ;
  var dName = now.getDay() +1;
  var dayNr = now.getDate();
  var yearNr=now.getYear();
  if(dName==1) {Day = "Domingo";}
  if(dName==2) {Day = "Segunda-feira";}
  if(dName==3) {Day = "Terça-feira";}
  if(dName==4) {Day = "Quarta-feira";}
  if(dName==5) {Day = "Quinta-feira";}
  if(dName==6) {Day = "Sexta-feira";}
  if(dName==7) {Day = "Sábado";}
  if(mName==1){Month = "Janeiro";}
  if(mName==2){Month = "Fevereiro";}
  if(mName==3){Month = "Março";}
  if(mName==4){Month = "Abril";}
  if(mName==5){Month = "Maio";}
  if(mName==6){Month = "Junho";}
  if(mName==7){Month = "Julho";}
  if(mName==8){Month = "Agosto";}
  if(mName==9){Month = "Setembro";}
  if(mName==10){Month = "Outubro";}
  if(mName==11){Month = "Novembro";}
  if(mName==12){Month = "Dezembro";}
  if(yearNr < 2000) {Year = 1900 + yearNr;}
  else {Year = yearNr;}
  var todaysDate =(" " + "São Paulo, " + dayNr + " de " + Month + " de " + Year  +  " - " + Day  );

document.getElementById("todaysDate").innerHTML = todaysDate;
}
</script>

<body>
<!-- A data entraria nesta DIV -->
<div id="todaysDate"></div>

</body>
</html>

0

Try as follows with JavaScript pure. Remember, however, that if you use jQuery can facilitate in the aesthetic issue of your code, other libraries handling and translation of dates too, it is always good to check if you are using a framework that already contains these included features, will save all these ifs.

var now = new Date();
var mName = now.getMonth() +1 ;
var dName = now.getDay() +1;
var dayNr = now.getDate();
var yearNr=now.getYear();
if(dName==1) {Day = "Domingo";}
if(dName==2) {Day = "Segunda-feira";}
if(dName==3) {Day = "Terça-feira";}
if(dName==4) {Day = "Quarta-feira";}
if(dName==5) {Day = "Quinta-feira";}
if(dName==6) {Day = "Sexta-feira";}
if(dName==7) {Day = "Sábado";}
if(mName==1){Month = "Janeiro";}
if(mName==2){Month = "Fevereiro";}
if(mName==3){Month = "Março";}
if(mName==4){Month = "Abril";}
if(mName==5){Month = "Maio";}
if(mName==6){Month = "Junho";}
if(mName==7){Month = "Julho";}
if(mName==8){Month = "Agosto";}
if(mName==9){Month = "Setembro";}
if(mName==10){Month = "Outubro";}
if(mName==11){Month = "Novembro";}
if(mName==12){Month = "Dezembro";}
if(yearNr < 2000) {Year = 1900 + yearNr;}
else {Year = yearNr;}
var todaysDate =(" " + "São Paulo, " + dayNr + " de " + Month + " de " + Year  +  " - " + Day  );

document.getElementById('todaysDate').innerHTML = todaysDate;
<!DOCTYPE html>
<html>

<body>
<!-- A data entraria nesta DIV -->
<div id="todaysDate">"  "</div>

</body>
</html>

Example with jQuery:

<!DOCTYPE html>
<html>
    <body>
        <!-- A data entraria nesta DIV -->
        <div id="todaysDate">"  "</div>
    </body>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        $( document ).ready(function() {
            var now = new Date();
            var mName = now.getMonth() +1 ;
            var dName = now.getDay() +1;
            var dayNr = now.getDate();
            var yearNr=now.getYear();
            if(dName==1) {Day = "Domingo";}
            if(dName==2) {Day = "Segunda-feira";}
            if(dName==3) {Day = "Terça-feira";}
            if(dName==4) {Day = "Quarta-feira";}
            if(dName==5) {Day = "Quinta-feira";}
            if(dName==6) {Day = "Sexta-feira";}
            if(dName==7) {Day = "Sábado";}
            if(mName==1){Month = "Janeiro";}
            if(mName==2){Month = "Fevereiro";}
            if(mName==3){Month = "Março";}
            if(mName==4){Month = "Abril";}
            if(mName==5){Month = "Maio";}
            if(mName==6){Month = "Junho";}
            if(mName==7){Month = "Julho";}
            if(mName==8){Month = "Agosto";}
            if(mName==9){Month = "Setembro";}
            if(mName==10){Month = "Outubro";}
            if(mName==11){Month = "Novembro";}
            if(mName==12){Month = "Dezembro";}
            if(yearNr < 2000) {Year = 1900 + yearNr;}
            else {Year = yearNr;}
            var todaysDate =(" " + "São Paulo, " + dayNr + " de " + Month + " de " + Year  +  " - " + Day  );

            $('#todaysDate').text(todaysDate);
        });

    </script>
</html>
  • 1

    You say that "jQuery would make it easier" in this case. How do you suggest this? I can’t see the benefit you mention.

  • Functional benefit no, I refer only to writing the same code

  • 4

    90% of the above code is done with if/else and the Javascript date API. I reiterate that I can’t see a great improvement with the use of jQuery. That’s why the doubt. :)

  • Really, I consider more as a "shortcut" to some things and in some cases an extra script to weigh in the load

Browser other questions tagged

You are not signed in. Login or sign up in order to post.