如何获取当前日期和时间作为常量?

发布于 2025-01-17 14:10:52 字数 175 浏览 0 评论 0原文

我试图在应用程序首次加载时获取当前日期和时间作为全局常量变量。然后使用这个常量变量来调用 GET 方法。

在JS中有没有办法做到这一点?

我试过:

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

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");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

中二柚 2025-01-24 14:10:52

您的常量应该在页面加载时初始化,而不是在http请求上初始化

您应该将值存储在变量中,而不是在执行http请求时回忆moment()

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>

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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文