欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

util.js工具函数的收集封装

程序员文章站 2022-07-12 21:10:28
...
function friendlyDate(timestamp) {
	var formats = {
		'year': '%n% 年前',
		'month': '%n% 月前',
		'day': '%n% 天前',
		'hour': '%n% 小时前',
		'minute': '%n% 分钟前',
		'second': '%n% 秒前',
	};

	var now = Date.now();
	var seconds = Math.floor((now - timestamp) / 1000);
	var minutes = Math.floor(seconds / 60);
	var hours = Math.floor(minutes / 60);
	var days = Math.floor(hours / 24);
	var months = Math.floor(days / 30);
	var years = Math.floor(months / 12);

	var diffType = '';
	var diffValue = 0;
	if (years > 0) {
		diffType = 'year';
		diffValue = years;
	} else {
		if (months > 0) {
			diffType = 'month';
			diffValue = months;
		} else {
			if (days > 0) {
				diffType = 'day';
				diffValue = days;
			} else {
				if (hours > 0) {
					diffType = 'hour';
					diffValue = hours;
				} else {
					if (minutes > 0) {
						diffType = 'minute';
						diffValue = minutes;
					} else {
						diffType = 'second';
						diffValue = seconds === 0 ? (seconds = 1) : seconds;
					}
				}
			}
		}
	}
	return formats[diffType].replace('%n%', diffValue);
}

function getDate() {
	let myDate = new Date()
	let month = myDate.getMonth()
	if (month < 10) {
		month = '0' + (month + 1)
	}
	let day = myDate.getDate()
	if (day < 10) {
		day = '0' + day
	}
	let date = myDate.getFullYear() + '-' + month + '-' + day
	return date
}

function getTime() {
	let myDate = new Date()
	let hour = myDate.getHours()
	if (hour < 10) {
		hour = '0' + hour
	}
	let min = myDate.getMinutes()
	if (min < 10) {
		min = '0' + min
	}
	let time = hour + ':' + min
	return time
}

module.exports = {
	friendlyDate: friendlyDate,
        getDate: getDate,
        getTime: getTime
}

main.js中挂载为全局方法

import { friendlyDate } from './common/util.js'
Vue.prototype.$friendlyDate = friendlyDate

 

相关标签: 插件 前端