Search code examples
javascripthtmldatetimemomentjsepoch

Turn epoch datetime textbox value to a 24h human date?


I have a first textbox that contains an epoch datetime stamp.

Because this format is not human readable, i decided to set it as readonly and hidden.

From that first textbox value, i would like to mirror its epoch value to a 24h human date that will be visible into a 2sd textbox.

Here is what i did so far, but it does not work :

( ~gpio_actual_schedule_event~ is automatically replaced by a datetime stamp by the server when the page loads )

HTML

<input type="hidden" value="~gpio_actual_schedule_event~" id="epoch_stamp" readonly >
<input type="text" id="converted_set_next_event" readonly >

At page load, i convert datetime stamp to human readable format with Javascript :

<script>
function epoch_to_24h_date(){   

var epochdate = new Date(~gpio_actual_schedule_event~ * 1); // multiply by 1000 for milliseconds
var date_string = epochdate.toLocaleString('en-GB');  // 24 hour format         
    }   
</script>

<script>
    window.onload= function(){

          epoch_to_24h_date();  
          document.getElementById('converted_set_next_event').value = date_string;  

        }   
</script>

https://jsfiddle.net/lcoulon/0qw06mjs/


Solution

  • The date_string variable is available only inside the epoch_to_24h_date function. You should return it:

    <script>
      function epoch_to_24h_date(){
        var epochdate = new Date(~gpio_actual_schedule_event~ * 1); // multiply by 1000 for milliseconds
        return epochdate.toLocaleString('en-GB');  // 24 hour format         
      }   
    </script>
    
    <script>
      window.onload= function(){
        document.getElementById('converted_set_next_event').value = epoch_to_24h_date();  
      }   
    </script>