在vue.js中获取当前时间和日期

iqjalb3h  于 2023-08-07  发布在  Vue.js
关注(0)|答案(4)|浏览(160)

我需要得到当前的时间和日期在网页上,我有它的JavaScript代码。不知道如何在vue.js中实现。我在这里附上代码示例。
html和纯js代码:

<html>
    <body>

        <h2>JavaScript new Date()</h2>
        <p id="timestamp"></p>

        <script>
            var today = new Date();
            var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
            var time = today.getHours() + ":" + today.getMinutes() + ":" + 
            today.getSeconds();
            var dateTime = date+' '+time;
            document.getElementById("timestamp").innerHTML = dateTime;
        </script>

    </body>
</html>

字符串
我需要在vue.js中实现,我应该在哪里包括安装或计算或方法?

ssgvzors

ssgvzors1#

因为目前的时间不依赖于任何数据变量,所以我们可以将其写在方法中,并在created中调用
阅读更多关于computed方法here
您可以复制并在CodingGround中运行它

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js">
      </script>
   </head>
   <body>
      <div id = "intro" style = "text-align:center;">
         <h1>{{ timestamp }}</h1>
      </div>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               timestamp: ""
            },
            created() {
                setInterval(this.getNow, 1000);
            },
            methods: {
                getNow: function() {
                    const today = new Date();
                    const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
                    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                    const dateTime = date +' '+ time;
                    this.timestamp = dateTime;
                }
            }
         });
      </script>
   </body>
</html>

字符串

js81xvg6

js81xvg62#

假设你有一个组件,比如Dashboard.vue,你可以使用getter:

<template>
  <v-container fluid>
    <h1>{{ timestamp }}</h1>
  </v-container>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class Dashboard extends Vue {
  get timestamp() {
    const today = new Date();
    const date = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate();
    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    const timestamp = date + ' ' + time;
    return timestamp;
  }
}
</script>

字符串

wmtdaxz3

wmtdaxz33#

我在vue js中想出了这个代码,你可以这样使用

var first_time = '09:00:00'
var today = new Date()
var now_date = (today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate());
var now_time = (today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()).toString()

if (now_time === first_time){
console.log('true')
}else(){
console.log('false')
}

字符串

thtygnil

thtygnil4#

你可以用这个来获取当前的一天:

"(new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substring(0, 10)"

字符串

相关问题