Home > Enterprise >  adding a live date to a website using html and css?
adding a live date to a website using html and css?

Time:02-19

I wanted to make it so when someone goes on the site, it displays the current date for them in the format of this example: January 15th, 2022 . I tried different scripts before but they all turn up in formats that I don't like.

CodePudding user response:

The best way to implement this is using Javascript. Javascript adds a new dimension to the websites. So, you either use vanilla Javascript or use third-party libraries like Moment.js

In your case, I suggest using vanilla Javascript since you won't deal with dates too much. Here is a code snippet that will help you out

function getCurrentDate() {
    let date;
    let dateTime;
  
    date = new Date;
    dateTime = date.toISOString().split("T")[0];

    document.querySelector("#display-date").textContent =  dateTime;
}

getCurrentDate();
<h1 id="display-date"></h1>

Also, remember to add a script tag at the end of the body tag to reference the Javascript code.

W3schools: W3schools tutorial script tag

CodePudding user response:

It has already been mentioned how to integrate the date into the tag. But what has not been said yet is that you should consider the order. I would put the date injection after an onl oad. This way I would be on the safe side, that as soon as the DOM is loaded, my JS can also address the selector.

window.onload = () => {    
  const el = document.getElementById('customDate');  
  el.innerHTML = (new Date).toISOString().split("T")[0];  
}
<div id="customDate">waiting...</div>

CodePudding user response:

You can do this with Java Script. Not without that.

const d = new Date();
document.getElementById("date").innerHTML = d;
<h2>Date</h2>

<p id="date"></p>

CodePudding user response:

<!-- Current Date -->
Current Date:
<input type="text" id="currentDate">
<br><br>
<script>
  var today = new Date();
  var date = today.getFullYear() '-' (today.getMonth() 1) '-' today.getDate();
  document.getElementById("currentDate").value = date;
</script>
<!-- Current Time -->
Current Time:
<input type="text" id="currentTime">
<br><br>
<script>
var today = new Date();
var time = today.getHours()   ":"   today.getMinutes()   ":"   today.getSeconds();
  document.getElementById("currentTime").value = time;
</script>
<!-- Current Date and Time -->
Get Current Date and Time Both:
<input type="text" id="currentDateTime">
<br><br>
<script>
  var today = new Date();
var date = today.getFullYear() '-' (today.getMonth() 1) '-' today.getDate();
var time = today.getHours()   ":"   today.getMinutes()   ":"   today.getSeconds();
var dateTime = date ' ' time;
  document.getElementById("currentDateTime").value = dateTime;
</script>

  • Related