muz-doraemon
Version:
自主开发的UniApp组件——Жидзин(Zidjin)系列组件库。
77 lines (72 loc) • 3.46 kB
JavaScript
/** x-date V0.2.1.20230331 简化版 by Sieyoo, 赵向明 */
const XDate = function () {};
/**
* function format 将日期字符串或时间戳转化为指定格式的字符串
* @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 例子:
* XDate.format("yyyy-mm-dd HH:ii:ss.fff") // ==> 1931-09-18 22:20:00.423
* XDate.format("yy-m-d H:i:s.f") // ==> 31-9-18 22:20:0.4
* XDate.format("yyyy年mm月dd日", '1931-09-18 22:20:00') // ==> 1931年09月18日
*/
XDate.format = function (format = 'yyyy-mm-dd HH:ii:ss.f', date = new 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.replace(/-/g, '/').replace('T', ' ').substr(0, 19)); // date是字符串,转/、替换T、删毫秒,兼容苹果系统
}
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"或"yyyy-mm-ddTHH:ii:ss"
* @return {int} timestamp 时间戳
* @example 例子:
* XDate.toTimeStamp('1931-09-18 22:20:00') ==> -1208252400
* XDate.toTimeStamp('1988-08-13 13:00:00') ==> 587451600
*/
XDate.toTimeStamp = function (dateStr = '1931-09-18 22:20: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 = '1931-09-18 22:20: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;