0
var unixtime =356674566

var newDate = new Date();

newDate.setTime(unixtime * 1000);

dateString = newDate.toUTCString();

document.getElementById("time").innerHTML = dateString;

I wanted to give h1 element text(not input text) as an input to var unix timestamp..is there any way to do that?

1
  • Can you provide some HTML code? Commented Feb 4, 2019 at 2:43

1 Answer 1

3

You can give the h1 element an id and use document.getElementById to get the h1 element. Then you can use .textContent to get the text within the h1 tag. Finally, you can use a + to convert the string retrieved from textContent to a number.

See working example below:

document.addEventListener('DOMContentLoaded', function() {
  var unixtime = +document.getElementById('unix').textContent;
  var newDate = new Date();

  newDate.setTime(unixtime * 1000);
  dateString = newDate.toUTCString();

  document.getElementById("time").textContent = dateString;
});
<h1 id="unix">356674566</h1>
<p>Date: <span id="time"></span></p>

Sign up to request clarification or add additional context in comments.

1 Comment

@SalmanDev try my updated version. I added an event lister to the script so that it only fires when the page contents have loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.