/** * Created by jiachenpan on 16/11/18. */ import md5 from 'js-md5'; // 时间转换格式 export function parseTime(time, cFormat) { if (arguments.length === 0) { return null; } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'; let date; if (typeof time === 'object') { date = time; } else { if (('' + time).length === 10) time = parseInt(time) * 1000; date = new Date(time); } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() }; const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => { let value = formatObj[key]; if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]; if (result.length > 0 && value < 10) { value = '0' + value; } return value || 0; }); return time_str; } // 判断多久之前 export function formatTime(time, option) { time = +time * 1000; const d = new Date(time); const now = Date.now(); const diff = (now - d) / 1000; if (diff < 30) { return '刚刚'; } else if (diff < 3600) { // less 1 hour return Math.ceil(diff / 60) + '分钟前'; } else if (diff < 3600 * 24) { return Math.ceil(diff / 3600) + '小时前'; } else if (diff < 3600 * 24 * 2) { return '1天前'; } if (option) { return parseTime(time, option); } else { return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'; } } /** * 获取dom对象偏移位置 设置初始位置 * @param {*} dom - 需要获取的dom * @param {*} isFixed - 父级是否position: fixed */ export function getDomOffset(dom) { let pol = 0; let pot = 0; let offsetLeft = 0; let offsetTop = 0; while (dom) { if (pol != dom.offsetLeft) { offsetLeft += dom.offsetLeft; pol = dom.offsetLeft; } if (pot != dom.offsetTop) { offsetTop += dom.offsetTop; pot = dom.offsetTop; } dom = dom.offsetParent; } const offset = { x: offsetLeft, y: offsetTop }; return offset; } /** * 矩形碰撞检测 */ export function checkRectCollision(rect1, rect2) { const center1 = { x: rect1.point.x + rect1.width / 2, y: rect1.point.y + rect1.height / 2 }; const center2 = { x: rect2.point.x + rect2.width / 2, y: rect2.point.y + rect2.height / 2 }; if ( // 横向判断 和 纵向判断 Math.abs(center1.x - center2.x) < rect1.width / 2 + rect2.width / 2 && Math.abs(center1.y - center2.y) < rect1.height / 2 + rect2.height / 2 ) { return true; } return false; } export function getSessionId() { return md5([Math.random().toFixed(5), +new Date()].join('_')); } /* * 获取倒计时 * data 目标时间 */ export function getCountTime(data) { const stationDate = parseInt(data); const date = Date.parse(new Date()) / 1000; const time = stationDate - date; if (time > 0) { let h = Math.floor(time / (60 * 60)); let m = Math.floor(time / 60) - (h * 60); let s = Math.floor(time) - (h * 60 * 60) - (m * 60); if (h <= 9) h = '0' + h; if (m <= 9) m = '0' + m; if (s <= 9) s = '0' + s; return `${h}:${m}:${s}`; } else { return -1; } }