javascriptunixepoch

Epoch class functionality


I am trying to make JavaScript code where I can put a <span class="epoch>(unix timestamp)</span> and it will set it to the timestamp in the user's timezone.

So far I have this code:

let epoch = document.getElementsByClassName("epoch");
for (var i = 0; i < epoch.length; i++) {
    let d = new Date(parseInt(epoch.item(i))).toDateString({ weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' });
    epoch.item(i).innerText = d;
}

I tried replacing epoch.item(i).innerText = d; with alert(d); but that still didn't work.

HTML (not full version but still has the same things):

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Mesure73L</title>
  <link href="index.css?v=1" rel="stylesheet" type="text/css" />
  <script src="index.js?v=1" defer></script>
  <script src="https://mesure.x10.mx/public_assets/main.js?v=1" defer></script>
  <script id="mobile_navbar"></script>
  <link rel="icon" type="image/x-icon" href="favicon.png">
</head>

<body>
  <script id="replace_with_navbar" src="https://mesure.x10.mx/public_assets/navbar.js?v=1"></script>
  <div id="content">
    <p><span id="epoch">1700523189</span></p>
  </div>
</body>

</html>

Solution

  • Original Answer

    There are a few things to correct and improve in your JavaScript code to achieve the functionality you're looking for.

    1. Typo in getElementsByClassName: The method name should be getElementsByClassName (plural) instead of getElementByClassName (singular).

    2. Parsing the Timestamp: The parseInt function should be called with the innerText of the epoch element to convert the epoch timestamp string to a number.

    3. Date Formatting: The toDateString method doesn't accept any arguments. To format the date, you should use toLocaleDateString instead, which allows specifying formatting options.

    4. You are using an ID as epoch and calling a Class.

    let epochs = document.getElementsByClassName("epoch");
    for (var i = 0; i < epochs.length; i++) {
        let timestamp = parseInt(epochs[i].innerText, 10);
        let date = new Date(timestamp * 1000); // Convert to milliseconds
        let formattedDate = date.toLocaleDateString(undefined, { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric', 
            hour: '2-digit', 
            minute: '2-digit', 
            second: '2-digit', 
            timeZoneName: 'short' 
        });
        epochs[i].innerText = formattedDate;
    }
    

    Explanation:

    • getElementsByClassName("epoch") returns a live HTMLCollection of found elements with the class name "epoch".
    • parseInt(epochs[i].innerText, 10) parses the inner text of each element as an integer in base 10 (epoch timestamp).
    • new Date(timestamp * 1000) creates a new Date object from the epoch timestamp. Epoch time is in seconds, but JavaScript's Date object constructor requires milliseconds, hence the multiplication by 1000.
    • toLocaleDateString(undefined, {...}) formats the date according to the user's local settings (undefined makes it use the user's locale). The options object specifies how various parts of the date should be represented.
    • Finally, epochs[i].innerText = formattedDate replaces the inner text of each span with the formatted date string.

    JSFiddle Link: https://jsfiddle.net/Termato/d1ytopuq/1/


    Updated:

    Use the following code:

    <span class="epoch">(epoch timestamp)</span>
    

    And then for the JavaScript:

     window.onload = function() {
        // Get the current timestamp in seconds
        var milliseconds = new Date().getTime();
    
        // Create a Date object from the current timestamp
        let date = new Date(milliseconds * 1000);
    
        // Find the span element and set its content
        let epochSpan = document.querySelector('.epoch');
        if (epochSpan) {
            epochSpan.innerText = date;
        }
    };
    

    You can see the JSFiddle Here: https://jsfiddle.net/Termato/hr7ytf1p/5/

    In your question, you reference a Class but in your code epoch is an ID. This wont work. Either make <span class="epoch"> OR change the javascript to target the ID: document.querySelector('#epoch');

    See this JS Fiddle for example: https://jsfiddle.net/Termato/zmcaoxb9/2/