uniapp小程序时间格式封装

1.封装工具类文件

// utils.js
export default{
    //时间格式化 
    dateFormat(time, flag) {
        // time  时间戳 单位秒
		// flag=1   年-月-日 时-分
		// flag=2   年-月-日
		// flag=3   刚刚/分钟前/小时前/年-月-日
		time = +time * 1000
		let date = new Date(time);
		let now = new Date().getTime();
		let diff = (now - date) / 1000
		let year = date.getFullYear();
		let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
		let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

		if (flag == 1) {
			return year + "年" + month + "月" + day + "日" + hours + ":" + minutes;
		} else if (flag == 2) {
			return year + '-' + month + '-' + day;
		} else if (flag == 3) {
			if (diff < 30) {
				return '刚刚'
			} else if (diff < 3600) {
				return Math.ceil(diff / 60) + '分钟前'
			} else if (diff < 3600 * 24) {
				return Math.ceil(diff / 3600) + '小时前'
			} else {
				return year + '-' + month + '-' + day
			}
		}
	}
}

2.全局挂载

// main.js
import App from './App'
import Vue from 'vue'
import tool from '@/utils/utils.js' //引入


App.mpType = 'app'
Vue.prototype.$tool = tool  //  挂载
const app = new Vue({
	...App,
	store
})
app.$mount()

3.页面使用


// this.$tool.dateFormat(time, 1) 可以直接在页面中使用 参数自定皆为必传项

onShow() {
           // time 为时间戳 注意是秒!毫秒的话要/1000
		this.nowTime = this.$tool.dateFormat(time, 1);
	},

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值