'How to get current date and time as a constant?

I am trying to get the current date and time as a global constant variable when the app first load. Then use this constant variable to call GET method.

Is there a way to do this in JS?

I tried:

const time = moment().format("MMMM DD YYYY, hh:mm:ss");


Solution 1:[1]

your constant should be initialize at the loading of the page and not on the http request

you should store the value in a variable and not recall moment() when you perform your http request

const time = moment().format("MMMM DD YYYY, hh:mm:ss");

function displayInitTime() {
  console.log(time);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<button onClick="displayInitTime()">click me</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jeremy-denis