整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

如何在JavaScript/Vue中获取当前时间并格式化输出精确到时分秒

ue 示例

在JavaScript或Vue中获取当前时间并格式化输出到精确的时分秒,你可以使用Date对象结合字符串拼接或者模板字符串来实现。下面是一个简单示例,展示了如何在Vue中完成这项任务:

<template>
  <div>
    <p>当前时间:{{ formattedTime }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formattedTime: ''
    };
  },
  mounted() {
    this.updateTime();
    setInterval(this.updateTime, 1000); // 每秒更新一次
  },
  methods: {
    updateTime() {
      const now = new Date();
      // 使用模板字符串进行格式化
      this.formattedTime = `${now.getFullYear()}-${this.padZero(now.getMonth() + 1)}-${this.padZero(now.getDate())} ${this.padZero(now.getHours())}:${this.padZero(now.getMinutes())}:${this.padZero(now.getSeconds())}`;
    },
    // 辅助函数,用于补零操作
    padZero(num) {
      return num < 10 ? '0' + num : num;
    }
  },
  beforeDestroy() {
    // 清除定时器,避免内存泄漏
    clearInterval(this.timer);
  }
};
</script>

在这个示例中,我们在Vue组件的mounted生命周期钩子中初始化了一个定时器,每秒钟调用updateTime方法来更新当前时间,并在组件销毁前通过beforeDestroy钩子清理定时器。

updateTime方法中,我们创建了一个新的Date对象来获取当前时间,然后使用模板字符串和辅助函数padZero来确保月份、日期、小时、分钟和秒数如果是个位数,则在其前补零,以便格式统一和美观。

这样,页面上就会显示一个实时更新的当前时间,格式为“年-月-日 时:分:秒”。

Vue3 Composition API 示例

在Vue3中,虽然一些API和写法有所变化,但获取和格式化当前时间的基本逻辑与Vue2相似。以下是使用Vue3 Composition API的一个示例:

<template>
  <div>
    <p>当前时间:{{ formattedTime }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const formattedTime = ref('');
let timer = null;

const updateTime = () => {
  const now = new Date();
  formattedTime.value = `${now.getFullYear()}-${padZero(now.getMonth() + 1)}-${padZero(now.getDate())} ${padZero(now.getHours())}:${padZero(now.getMinutes())}:${padZero(now.getSeconds())}`;
};

const padZero = (num) => {
  return num < 10 ? '0' + num : num;
};

onMounted(() => {
  updateTime();
  timer = setInterval(updateTime, 1000); // 每秒更新一次
});

onBeforeUnmount(() => {
  // 清除定时器
  clearInterval(timer);
});
</script>

在这个Vue3的示例中,我们使用了Composition API来管理状态和生命周期钩子。ref用于定义响应式数据formattedTime,而onMounted和onBeforeUnmount分别替代了Vue2中的mounted和beforeDestroy生命周期钩子。

updateTime函数和padZero辅助函数的功能与Vue2示例相同,用于获取当前时间并进行格式化处理,以及在数字小于10时前面添加零。

这样,你就可以在Vue3应用中实现实时更新并格式化显示当前时间的功能。

TypeScript 公共函数封装

使用TypeScript可以为你的代码增加类型安全。下面是如何封装一个获取并格式化当前时间的公共函数,这个函数可以在Vue3的项目中作为公共方法使用。

首先,在你的Vue3项目的某个公用文件夹(如src/utils)下创建一个名为dateTimeUtils.ts的文件,并编写如下代码:

// src/utils/dateTimeUtils.ts

export function formatCurrentTime(): string {
  const now = new Date();
  return `${now.getFullYear()}-${padZero(now.getMonth() + 1)}-${padZero(now.getDate())} ${padZero(now.getHours())}:${padZero(now.getMinutes())}:${padZero(now.getSeconds())}`;
}

function padZero(num: number): string {
  return num < 10 ? '0' + num : num.toString();
}

这个模块导出了一个formatCurrentTime函数,它返回当前时间的格式化字符串。同时,内部使用了padZero辅助函数来保证数字的格式正确。

然后,在你的Vue3组件中,你可以这样使用这个公共函数:

// 某个Vue3组件.vue文件

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { formatCurrentTime } from '@/utils/dateTimeUtils'; // 根据你的实际路径调整

const formattedTime = ref('');

onMounted(() => {
  formattedTime.value = formatCurrentTime();
  setInterval(() => {
    formattedTime.value = formatCurrentTime();
  }, 1000);
});
</script>

<template>
  <div>
    <p>当前时间:{{ formattedTime }}</p>
  </div>
</template>

这里,我们导入了formatCurrentTime函数,并在组件挂载时设置初始值,之后每秒更新一次显示的时间。注意,为了避免潜在的内存泄漏,如果组件需要销毁时停止时间更新,你可能还需要在适当的生命周期钩子中清除定时器,正如之前Vue2和Vue3 Composition API示例中所示。不过,在此示例中为了保持简洁,省略了该部分代码。

段时间发的五子棋的游戏很多小伙伴都私聊让再做个,今天小猿圈web前端讲师为大家分享的是CSS3动画练习案例:用CSS3做个钟表,想玩的小伙伴记得自己运行一下呦。

自学CSS3属性之后,我们来用一个小案例进行一个综合练习,这个案例主要是动画的应用,我们就用纯css动画做一个能走字的钟表。

首先我们来准备HTML来布局一下:

<body>

<div class="clock">

<div class="line1"></div>

<div class="line2"></div>

<div class="line3"></div>

<div class="line4"></div>

<div class="line5"></div>

<div class="line6"></div>

<div class="cent"></div>

<div class="cover"></div>

<div class="hour"></div>

<div class="minute"></div>

<div class="seconds"></div>

</div>

</body>

布局很简单,六根直线通过旋转一定角度做刻度一个中间小圆点,一个遮罩来盖住六根直线的中间部分,使直线变成刻度,后面三个是时分秒针。

下面通过CSS把钟表的大概样子设置出来。

.clock {

/* 创建圆形盒子当做表盘 */

width: 200px;

height: 200px;

margin: 100px auto;

position: relative;

border: 10px solid #000;

border-radius: 50%;

}

.clock div:nth-child(-n+6) {

/* 选中前6个子元素做出6条线当做表的刻度 */

width: 6px;

height: 200px;

background-color: #aaa;

position: absolute;

left: 50%;

margin-left:-3px;

}

/* 让6条线递增旋转30度 */

.clock div:nth-child(1) {

transform: rotate(30deg);

}

.clock div:nth-child(2) {

transform: rotate(60deg);

}

.clock div:nth-child(3) {

transform: rotate(90deg);

background-color: #333;

}

.clock div:nth-child(4) {

transform: rotate(120deg);

}

.clock div:nth-child(5) {

transform: rotate(150deg);

}

.clock div:nth-child(6) {

transform: rotate(0deg);

background-color: #333;

}

/* 中心小圆点 */

.cent {

width: 20px;

height: 20px;

background-color: #000;

border-radius: 50%;

position:absolute;

z-index: 3;

left: 50%;

top:50%;

margin: -10px 0 0 -10px;

z-index:2;

}

/* 遮住线的中间部分,让线成为刻度 */

.cover {

width: 180px;

height: 180px;

border-radius: 50%;

background-color: #fff;

position:absolute;

left: 50%;

top:50%;

margin:-90px 0 0 -90px;

}

后面加上中心圆点和遮罩,让它看起来像个表盘。

接下来我们就可以准备表针和动画了。

/* 时针制作 */

.hour {

width: 6px;

height: 50px;

background-color: #000;

position:absolute;

left: 50%;

top:100px;

margin-left: -3px;

animation: clockrotate 43200s steps(43200) infinite linear;

transform-origin: top center;

}

/* 分针制作 */

.minute {

width: 60px;

height: 6px;

background-color: #555;

position:absolute;

left:40px;

top:50%;

margin-top: -3px;

animation: clockrotate 3600s steps(3600) infinite;

transform-origin: center right;

}

/* 秒针制作 */

.seconds {

width: 4px;

height: 70px;

background-color:red;

position: absolute;

left:50%;

top:30px;

margin-left: -2px;

animation: clockrotate 60s steps(60) infinite ;

transform-origin: bottom center;

}

/* 设置动画序列 */

@keyframes clockrotate {

form{

}

to {

transform: rotate(360deg);

}

}

设置每个针的动画是旋转360度,根据时、分、秒来计算动画执行完毕需要的时间和步数,加个infinite无限执行,另外还要注意表针旋转的中心点设置。

上述就是小猿圈老师针对CSS3动画练习案例:用CSS3做个钟表介绍,相信你对web前端也是有一定的了解的,如果遇到不会的问题可以到小猿圈去寻找答案的,里面有最新最全面的视频教程等你来学习,只要你想学习编程这里都有。

时器类型及语法

  • setTimeout 只执行一次的定时器
  • clearTimeout 关闭执行一次的定时器
  • setInterval 反复执行的定时器
  • clearInterval 关闭反复执行的定时器

简单用法:

//定时器调用函数,并给定时器命名
var time1 = setTimeout(myalert,2000); 
var time2 = setInterval(myalert,2000);
//停止指定定时器
clearTimeout(time1);
clearInterval(time2);
function myalert(){
 alert('ok!');
}
//简写(匿名函数代替即可)
var time1 = setTimeout(
 function(){
 alert('ok!');
 },2000);

实用的例子:

1、 动态显示当前时间

效果图: