/** * 早安电台 — 通用工具函数 */ /** * 秒数格式化为 mm:ss * @param {number} seconds - 总秒数 * @returns {string} - 如 "01:30" */ function formatTime(seconds) { seconds = Math.floor(seconds || 0) var min = Math.floor(seconds / 60) var sec = seconds % 60 return padZero(min) + ':' + padZero(sec) } /** * 补零 */ function padZero(num) { return num < 10 ? '0' + num : '' + num } /** * 日期格式化 * @param {Date|string} date * @param {string} [format='YYYY-MM-DD'] * @returns {string} */ function formatDate(date, format) { if (typeof date === 'string') { date = new Date(date.replace(/-/g, '/')) } format = format || 'YYYY-MM-DD' var year = date.getFullYear() var month = padZero(date.getMonth() + 1) var day = padZero(date.getDate()) return format .replace('YYYY', year) .replace('MM', month) .replace('DD', day) } /** * 获取星期几 * @param {Date} [date] * @returns {string} 周一~周日 */ function getWeekDay(date) { date = date || new Date() var days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] return days[date.getDay()] } /** * 获取今天的日期字符串 YYYY-MM-DD */ function getTodayStr() { return formatDate(new Date()) } /** * 获取友好的日期显示 * @param {string} dateStr - YYYY-MM-DD * @returns {string} 如 "今天"、"昨天"、"3月1日" */ function getFriendlyDate(dateStr) { var today = getTodayStr() if (dateStr === today) return '今天' var yesterday = new Date() yesterday.setDate(yesterday.getDate() - 1) if (dateStr === formatDate(yesterday)) return '昨天' var d = new Date(dateStr.replace(/-/g, '/')) return (d.getMonth() + 1) + '月' + d.getDate() + '日' } /** * 日期字符串替换 - 为 . */ function dateToDot(dateStr) { return (dateStr || '').replace(/-/g, '.') } /** * 获取日期显示 X月X日 */ function getDateDisplay(date) { date = date || new Date() return (date.getMonth() + 1) + '月' + date.getDate() + '日' } /** * 节流函数 */ function throttle(fn, delay) { var timer = null return function () { if (timer) return var args = arguments var context = this timer = setTimeout(function () { fn.apply(context, args) timer = null }, delay) } } module.exports = { formatTime, padZero, formatDate, getWeekDay, getTodayStr, getFriendlyDate, dateToDot, getDateDisplay, throttle }