UNPKG

muz-uni

Version:

自主开发的UniApp组件——Жидзин(Zidjin)系列组件库。

83 lines (75 loc) 3.19 kB
/** x-date V0.2.0 简化版 by Sieyoo, 赵向明 */ const XDate = function() {}; /** * function format 对Date的扩展,将 Date 转化为指定格式的String * @param {string} format 格式 * @param {Date, timestamp, string} date 要格式化的时间 JS Date类型 或 时间戳 * @desc 符号定义 * 月(m)、日(d)、小时(H)、分(i)、秒(s)、可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(f)能用 1-3 个占位符 * @return {string}   格式化的时间字符串 * @example 例子: * (new Date()).Format("yyyy-mm-dd HH:ii:ss.fff") ==> 2006-07-02 08:09:04.423 * (new Date()).Format("yyyy-M-d H:m:s.S") ==> 2006-7-2 8:9:4.18 */ XDate.format = function(format = "yyyy-mm-dd HH:ii:ss.f", date) { //author: meizz // 自动判断date并转换Date实例 if(date === undefined){ date = new Date() } else if (typeof(date) === 'number' || (typeof(date) === 'string' && !isNaN(date))){ date = new Date(parseInt(date)*1000) // date是时间戳 } else if (typeof(date) === 'string'){ date = XDate.toDate(date) // date是字符串 } if(!(date instanceof Date)){ return; } var o = { "m+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "H+": date.getHours(), //小时 "i+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "f": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return format; } /** * function toTimeStamp 转为时间戳 * @param {string} dateStr 要格式化的时间字符串,格式必须是"yyyy-mm-dd HH:ii:ss" * @return {int} timestamp 时间戳 * @example 例子: * XDate.toTimeStamp('2015-03-05 17:59:00') ==> 1425549540 * XDate.toTimeStamp('2015-03-05T17:59:00') ==> 1425549540 */ XDate.toTimeStamp = function(dateStr = '2015-03-05 17:59:00') { dateStr.replace('T', ' '); dateStr = dateStr.substring(0, 19); dateStr = dateStr.replace('-', '/'); let timestamp = new Date(dateStr).getTime()/1000; return timestamp; } /** * function toDate 将字符串转为时间类型 * @param {string} dateStr 要格式化的时间字符串,格式必须是"yyyy-mm-dd HH:ii:ss"或"yyyy-mm-ddTHH:ii:ss" * @return {Date} date 日期类型 * @example 例子: * XDate.toDate('2022-12-01 00:00:00') ==> Thu Dec 01 2022 00:00:00 GMT+0800 (中国标准时间) * XDate.toDate('2022-12-01T00:00:00.965').toLocaleString(); ==> 2022/12/1 00:00:00 */ XDate.toDate = function(dateStr = '2015-03-05 17:59:00') { // dateStr = dateStr.substring(0, 19); dateStr = dateStr.replace('T', ' ').replaceAll('-', '/'); let timestamp = new Date(dateStr).getTime(); let date = new Date(timestamp); return date; } export default XDate