vue 获取当前时间 用于不同格式

本文详细介绍了一种使用JavaScript进行时间日期格式化的实用方法,包括如何获取当前时间的年、月、日、时、分、秒,并将其格式化为统一的字符串格式。此外,还介绍了如何将此功能作为全局方法挂载到Vue实例中,以便在Vue项目中方便地调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

export function getTime(){
	  let currentdate=[]
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      //以下代码依次是获取当前时间的年月日时分秒
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      var minute = date.getMinutes();
      var hour = date.getHours();
      var second = date.getSeconds();
      //固定时间格式
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      if (hour >= 0 && hour <= 9) {
          hour = "0" + hour;
      }
      if (minute >= 0 && minute <= 9) {
          minute = "0" + minute;
      }
      if (second >= 0 && second <= 9) {
          second = "0" + second;
      }
	  currentdate=[parseInt(year),parseInt(month),parseInt(strDate),parseInt(hour),parseInt(minute),parseInt(second)]
	  return currentdate;
}

然后在main.js应用

import { getTime } from '@/utils/unit'
// 全局方法挂载
Vue.prototype.getTime=getTime

然后在text.vue页面

const currentTime=this.getTime()
//年月日 时分秒
const dataTime=currentTime[0]+"-"+currentTime[1]+"-"+
currentTime[2]+" "+currentTime[3]+" :"+currentTime[4]+":"+currentTime[5]

//年月
const dataTime=currentTime[0]+"/"+currentTime[1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值