UNPKG

cnwy-js-util

Version:

js常见的函数工具库

120 lines (109 loc) 3.16 kB
export function getDate(nDays) { // 获取当前日期 let date = new Date(); // 如果传参,则将日期设置为 nDays 天前 if (nDays !== undefined) { date.setDate(date.getDate() - nDays); } // 格式化日期为 YYYY-MM-DD 格式 let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); month = month < 10 ? '0' + month : month; day = day < 10 ? '0' + day : day; return year + '-' + month + '-' + day; } /** * 表格时间格式化 */ export function formatDate(cellValue) { if (cellValue == null || cellValue == '') return ''; var date = new Date(cellValue); var year = date.getFullYear(); var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1; var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(); var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(); return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds; } /** * @param {number} time * @param {string} option * @returns {string} */ export function formatTime(time, option) { if (('' + time).length === 10) { time = parseInt(time) * 1000; } else { time = +time; } 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() + '分' ); } } /** * @param {string} input value * @returns {number} output value */ export function byteLength(str) { // returns the byte length of an utf8 string let s = str.length; for (var i = str.length - 1; i >= 0; i--) { const code = str.charCodeAt(i); if (code > 0x7f && code <= 0x7ff) s++; else if (code > 0x7ff && code <= 0xffff) s += 2; if (code >= 0xdc00 && code <= 0xdfff) i--; } return s; } /** * @param {Array} actual * @returns {Array} */ export function cleanArray(actual) { const newArray = []; for (let i = 0; i < actual.length; i++) { if (actual[i]) { newArray.push(actual[i]); } } return newArray; } /** * @param {string} type * @returns {Date} */ export function getTime(type) { if (type === 'start') { return new Date().getTime() - 3600 * 1000 * 24 * 90; } else { return new Date(new Date().toDateString()); } }