@farris/expression-engine-vue
Version:
1,481 lines (1,480 loc) • 57.8 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultFunctions = void 0;
class DefaultFunctions {
constructor(context) {
this.context = context;
}
// 根据链式属性名获取属性值
GetChainedPropertyValue(chainedPropName) {
return this.eval(`${chainedPropName};`)();
}
GetContextParameter(propertyName) {
return this.eval(`${propertyName}`)();
}
GetSessionValue(propertyName) {
return this.eval(`${propertyName}`)();
}
eval(expr, arg) {
const contexts = this.context && this.context.contexts || {};
const args = contexts.arguments || arg || {};
let signature = '';
if (Array.isArray(args)) {
signature = args.join(',');
}
else {
signature = Object.keys(args).join(',');
}
const hasReturnStatement = expr.match(/([\s\r\n{;}]+return)|(^return)\s+/g);
if (!hasReturnStatement) {
expr = `return ${expr}`;
}
const scopeNames = Object.getOwnPropertyNames(contexts);
const scopeVariable = `__scope__${new Date().valueOf()}`;
return new Function(scopeVariable, `
${scopeNames.map((key) => `const ${key} = ${scopeVariable}['${key}'];`).join('\r\n')}
return function anonymous(${signature}) {
try{ \n${expr}\n }catch(e){console.error(e);}
};`)(contexts);
}
GetComputeJsonData(chainedPropName, propName) {
return this.eval(`${chainedPropName}.${propName}`)();
}
GetInjectedEntity(name) {
console.warn(`GetInjectedEntity不支持`);
return null;
}
/**
* 聚合类函数******************************************************************************************
*/
// 合计常量值
Sum(paramArray) {
let sum = 0;
for (let i = 0; i < paramArray.length; i++) {
sum += paramArray[i];
}
return sum;
}
IncludedInList(value, list) {
return list.includes(value);
}
ExistData(chainedPropName) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
return array && array.length>0 || false;
`)();
}
// 合计常量值
SumByProp(chainedPropName, propertyName) {
// 原始表达式 SumByProp("AEntity.abcs","a")
// like SumByProp("Entity.abcs","a");
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var result = array.reduce((total,item)=>{
var value = DefaultFunction.getPropValue(item,"${propertyName}");
if(Object.prototype.toString.call(value) === '[object Number]'){
total = total + value;
}
return total;
},0);
return result;
`)();
}
CountByProp(chainedPropName, propertyName) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var result = array.reduce((count,item)=>{
var value = DefaultFunction.getPropValue(item,"${propertyName}");
if(value!==null && value !== undefined){
count ++;
}
return count;
},0);
return result;
`)();
}
AvgByProp(chainedPropName, propertyName) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var result = array.reduce((total,item)=>{
var value = DefaultFunction.getPropValue(item,"${propertyName}");
if(Object.prototype.toString.call(value) === '[object Number]'){
total = total + value;
}
return total;
},0);
return parseFloat((result/array.length).toFixed(2));
`)();
}
MaxByProp(chainedPropName, propertyName) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var result = array.reduce((max,item)=>{
var value = DefaultFunction.getPropValue(item,"${propertyName}");
if(value!==undefined){
if(Object.prototype.toString.apply(value)!=="[object Number]"){
console.warn("对象"+JSON.stringify(item) + "中,属性 ${propertyName} 不是数字。");
}
max = max>=value?max:value;
}
return max;
},0);
return result;
`)();
}
MinByProp(chainedPropName, propertyName) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var result = array.reduce((min,item)=>{
var value = DefaultFunction.getPropValue(item,"${propertyName}");
if(value!==undefined && value!==null){
if(Object.prototype.toString.apply(value)!=="[object Number]"){
console.warn("对象"+JSON.stringify(item) + "中,属性 ${propertyName} 不是数字。");
}
min = min<=value?min:value;
}
return min;
},undefined);
return result;
`)();
}
/**
* 子表数据数量
* @param chainedPropName
*/
CountOfChild(chainedPropName) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
return array && array.length || 0;
`)();
}
/**
* 子表按属性排序
* @param chainedPropName
* @param propertyName
* @param orderType
* @returns
*/
SortChildData(chainedPropName, propertyName, orderType) {
orderType = orderType && (orderType.toLowerCase() === 'esc' || orderType.toLowerCase() === 'asc') ? 'asc' : 'desc';
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
if(array){
array =array.sort(DefaultFunction.comparator(['${propertyName}'],['${orderType}']));
}
return array;
`)();
}
/**
* 子表有无匹配的值
* @param chainedPropName
* @param propertyName
* @param propertyValue
*/
IsContainMatch(chainedPropName, propertyName, propertyValue) {
const compare = (value) => value === propertyValue;
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var index = array && array.findIndex((item)=>{
var value = DefaultFunction.getPropValue(item,'${propertyName}');
return compare(value);
});
return index!==-1;
`, ['compare'])(compare);
}
MinValueOfPeriod(chainedPropName, datePropertyName, valuePropertyName, start, end) {
if (!this.isValidDate(start) || !this.isValidDate(end)) {
return null;
}
const format = 'yyyy-MM-dd HH:mm:ss';
start = this.FormatDefineDate(format, start);
end = this.FormatDefineDate(format, end);
const condition = function (value, context) {
if (context.isValidDate(value)) {
value = context.FormatDefineDate(format, value);
}
return value >= start && value <= end;
};
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var results = array.filter(item=>{
var value = DefaultFunction.getPropValue(item,'${datePropertyName}');
return condition(value,DefaultFunction);
});
results = results.sort(DefaultFunction.comparator(['${valuePropertyName}'],['asc']));
if(results.length){
return DefaultFunction.getPropValue(results[0],'${valuePropertyName}');
}else{
return null;
}
`, ['condition'])(condition);
}
MaxValueOfPeriod(chainedPropName, datePropertyName, valuePropertyName, start, end) {
if (!this.isValidDate(start) || !this.isValidDate(end)) {
return null;
}
const format = 'yyyy-MM-dd HH:mm:ss';
start = this.FormatDefineDate(format, start);
end = this.FormatDefineDate(format, end);
const condition = function (value, context) {
if (context.isValidDate(value)) {
value = context.FormatDefineDate(format, value);
}
return value >= start && value <= end;
};
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var results = array.filter(item=>{
var value = DefaultFunction.getPropValue(item,'${datePropertyName}');
return condition(value,DefaultFunction);
});
results = results.sort(DefaultFunction.comparator(['${valuePropertyName}'],['asc']));
if(results.length){
return DefaultFunction.getPropValue(results.pop(),'${valuePropertyName}');
}else{
return null;
}
`, ['condition'])(condition);
}
AvgValueOfPeriod(chainedPropName, datePropertyName, valuePropertyName, start, end) {
if (!this.isValidDate(start) || !this.isValidDate(end)) {
return null;
}
const format = 'yyyy-MM-dd HH:mm:ss';
start = this.FormatDefineDate(format, start);
end = this.FormatDefineDate(format, end);
const condition = function (value, context) {
if (context.isValidDate(value)) {
value = context.FormatDefineDate(format, value);
}
return value >= start && value <= end;
};
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
var results = array.filter(item=>{
var value = DefaultFunction.getPropValue(item,'${datePropertyName}');
return condition(value,DefaultFunction);
});
results = results.map(item=>{
return DefaultFunction.getPropValue(item,'${valuePropertyName}');
});
if(results.length){
var total = results.reduce(function(total,current){
total = total + current;
return total;
},0);
return total / results.length;
}else{
return null;
}
`, ['condition'])(condition);
}
isValidDate(d) {
if (typeof d === 'string') {
d = new Date(d);
}
return d instanceof Date && !isNaN(d.valueOf());
}
getIterable(item) {
if (item && item.hasOwnProperty('__type__') && item.__type__ === 'BindingList') {
return item.toArray() || [];
}
if (item && item.hasOwnProperty('__type__') && item.__type__ === 'EntityList') {
return item.items || [];
}
if (item && item.hasOwnProperty('__type__') && (item.__type__ === 'List' || item.__type__ === 'Entity')) {
return item.__items__ || [];
}
if (Object.prototype.toString.apply(item) === "[object Array]") {
return item;
}
return [];
}
comparator(props, orders) {
return (item1, item2) => {
return props.reduce((result, prop) => {
if (result === 0) {
const order = ['asc'].includes(orders[props.indexOf(prop)]) ? 1 : -1;
let item1Value = this.getPropValue(item1, prop);
let item2Value = this.getPropValue(item2, prop);
if (item1Value === null || item1Value === undefined) {
item1Value = '';
}
if (item2Value === null || item2Value === undefined) {
item2Value = '';
}
if (typeof item1Value === 'string' && typeof item2Value === 'string') {
const localeCompareResult = item1Value.localeCompare(item2Value);
result = localeCompareResult * order;
}
else {
if (item1Value > item2Value) {
result = order * 1;
}
if (item1Value < item2Value) {
result = order * -1;
}
}
}
return result;
}, 0);
};
}
getPropValue(target, prop) {
const paths = prop.split('.').filter(p => p);
return paths && paths.reduce((result, path) => {
if (result && result.hasOwnProperty(path)) {
return result[path];
}
return undefined;
}, target);
}
isEqual(v1, v2) {
return v1 === v2;
}
hasProp(target, prop) {
const paths = prop.split('.').filter(p => p);
let isPropExist = true;
if (paths) {
for (let idx = 0; idx < paths.length; idx++) {
const path = paths[idx];
if (!target.hasOwnProperty(path)) {
isPropExist = false;
break;
}
target = target[path];
}
}
else {
isPropExist = false;
}
return isPropExist;
}
/**
* 字符串函数**********************************************************************************
*/
// 取子字符串
StringSubstring(originalString, startIndex, length) {
if (!originalString) {
return originalString;
}
return originalString.substr(startIndex, length);
}
Length(originalString) {
return originalString && originalString.hasOwnProperty('length') && originalString.length || 0;
}
// 取字符数
StringLength(originalString) {
return originalString && originalString.hasOwnProperty('length') && originalString.length || 0;
}
// 字符串替换
StringReplace(originalString, oldValue, newValue) {
return originalString.replace(new RegExp(oldValue, 'g'), newValue);
}
// 转为大写
ToUpper(originalString) {
if (!originalString) {
return originalString;
}
return originalString.toUpperCase();
}
// 转为小写
ToLower(originalString) {
if (!originalString) {
return originalString;
}
return originalString.toLowerCase();
}
// 返回字符串起始位置
IndexOf(originalString, value) {
if (originalString) {
return originalString.indexOf(value);
}
return -1;
}
// 返回字符串最后位置
LastIndexOf(originalString, value) {
return originalString.lastIndexOf(value);
}
// 去除字符串前面空格
TrimStart(originalString) {
return originalString && originalString.trimLeft();
}
// 去除字符串后面空格*
TrimEnd(originalString) {
return originalString && originalString.trimRight();
}
// 去除两边的空格
Trim(originalString) {
return originalString.trim();
}
// 取子字符串
SubString(originalString, startIndex, length) {
return this.StringSubstring(originalString, startIndex, length);
}
// 取字符数
GetStringLength(obj) {
return this.StringLength(obj);
}
// 字符串替换
Replace(originalString, oldValue, newValue) {
return this.StringReplace(originalString, oldValue, newValue);
}
// 唯一标识符
CreateGuid() {
let d = new Date().getTime();
const uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, ((c) => {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
}));
return uuid.toUpperCase();
}
// 转换为sql..................
CaseToSql(col) {
if (col == null || col === "") {
return ("参数为空");
}
const parameter = col.split(",");
if (parameter.length === 0 || parameter.length === 1) {
return ("函数CaseToSql,参数个数不正确");
}
let resultSql = " case " + parameter[0];
let temp = "";
// String[] valueStr = new String[2];
for (let i = 1; i <= parameter.length; i++) {
temp = parameter[i].replace("{", "");
temp = temp.replace("}", "");
const valueStr = temp.split(",");
resultSql = resultSql + " when " + valueStr[0] + " then " + valueStr[1];
}
resultSql += "end ";
return resultSql;
}
;
// 判断是否为空字符串
IsNullEmpty(str) {
if (str !== null && str !== "") {
return true;
}
return false;
}
// 2---10字符串相加............
Add(...str) {
let strTem = "";
for (let i = 0; i < str.length; i++) {
strTem += str[i];
}
return strTem;
}
/**
* 转化类函数*****************************************************************************************
*/
// 转为8位无符号整数
ToByte(obj) {
return obj >> 0;
}
// 转为字符串
ToStringX(obj) {
if (obj === null || obj === undefined) {
return obj;
}
if (typeof obj === 'string') {
return obj;
}
return JSON.stringify(obj);
}
// 转为日期时间
ToDateTime(obj) {
return new Date(obj);
}
// 转为布尔值
ToBoolean(obj) {
if (obj === null || obj === undefined) {
return obj;
}
if (typeof obj === 'boolean') {
return obj;
}
if (typeof obj === 'string') {
return obj.toLowerCase() === 'true';
}
return !!obj;
}
// 转为数值
ToDecimal(obj) {
return Number(obj);
}
ToBigDecimal(value) {
if (value === undefined) {
return 0;
}
return Number(value);
}
ToCustomBigDecimal(value, fractionDigits = 2) {
if (value === undefined) {
return 0;
}
return Number(value).toFixed(fractionDigits);
}
// 转为双精度浮点数
ToDouble(obj) {
return Number(obj);
}
// 转为单精度浮点数
ToFloat(obj) {
return Number(obj);
}
// 转为integer整数
ToInt16(obj) {
return parseInt(obj);
}
ToInt32(obj) {
return parseInt(obj);
}
// 转为中文大写金额
ToChineseMoney(money) {
// 汉字的数字
const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
// 基本单位
const cnIntRadice = ['', '拾', '佰', '仟'];
// 对应整数部分扩展单位
const cnIntUnits = ['', '万', '亿', '兆'];
// 对应小数部分单位
const cnDecUnits = ['角', '分', '毫', '厘'];
// 整数金额时后面跟的字符
const cnInteger = '整';
// 整型完以后的单位
const cnIntLast = '元';
// 最大处理的数字
const maxNum = 999999999999999.9999;
// 金额整数部分
let integerNum;
// 金额小数部分
let decimalNum;
// 输出的中文金额字符串
let chineseStr = '';
// 分离金额后用的数组,预定义
let parts;
if (money >= maxNum) {
// 超出最大处理数字
return '';
}
if (money == 0) {
chineseStr = cnNums[0] + cnIntLast + cnInteger;
return chineseStr;
}
// 转换为字符串
const moneyStr = money.toString();
if (moneyStr.indexOf('.') === -1) {
integerNum = moneyStr;
decimalNum = '';
}
else {
parts = moneyStr.split('.');
integerNum = parts[0];
decimalNum = parts[1].substr(0, 4);
}
// 获取整型部分转换
if (parseInt(integerNum, 10) > 0) {
let zeroCount = 0;
const IntLen = integerNum.length;
for (let i = 0; i < IntLen; i++) {
const n = integerNum.substr(i, 1);
const p = IntLen - i - 1;
const q = p / 4;
const m = p % 4;
if (n === '0') {
zeroCount++;
}
else {
if (zeroCount > 0) {
chineseStr += cnNums[0];
}
// 归零
zeroCount = 0;
chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
}
if (m === 0 && zeroCount < 4) {
chineseStr += cnIntUnits[q];
}
}
chineseStr += cnIntLast;
}
// 小数部分
if (decimalNum !== '') {
const decLen = decimalNum.length;
for (let i = 0; i < decLen; i++) {
const n = decimalNum.substr(i, 1);
if (n !== '0') {
chineseStr += cnNums[Number(n)] + cnDecUnits[i];
}
}
}
if (chineseStr === '') {
chineseStr += cnNums[0] + cnIntLast + cnInteger;
}
else if (decimalNum === '') {
chineseStr += cnInteger;
}
return chineseStr;
}
/**
* 判断函数****************************************************************************8
*/
// 是空值
IsNull(obj) {
return obj === null;
}
// 是空串
IsNullOrWhiteSpace(obj) {
if (obj === null || obj === "" || obj && obj.trim() === "") {
return true;
}
return false;
}
// 是非数字
IsNaN(obj) {
return isNaN(Number(obj));
}
// 是数字
IsNumber(obj) {
return !isNaN(Number(obj));
}
/**
* 数学类函数***************************************************************************************************
*/
// sin函数
sin(value) {
return Math.sin(value);
}
// cos函数
cos(value) {
return Math.cos(value);
}
// round函数
random(value) {
return Math.random();
}
// ceiling函数
ceil(value) {
return Math.ceil(value);
}
// abs函数
abs(value) {
return Math.abs(value);
}
floor(value) {
return Math.floor(value);
}
// 四舍五入
round(value, digits) {
return Math.round(value * Math.pow(10, digits)) / Math.pow(10, digits);
}
// 银行家算法舍入.............
bankerRound(value, num) {
if (typeof value !== "number") {
return undefined;
}
return value.toFixed(num);
}
/**
* 身份证函数**************************************************************************************************
*/
// 根据身份证号获取生日字符串
GetBirthday(idCard) {
const ret = this.IsIDcard(idCard);
if (!ret) {
return null;
}
let birthdayValue = "";
if (idCard.length === 15) {
// 15位身份证号码
birthdayValue = idCard.substring(6, 8);
if (Number(birthdayValue) < 10) {
birthdayValue = "20" + birthdayValue;
}
else {
birthdayValue = "19" + birthdayValue;
}
birthdayValue = birthdayValue + '-' + idCard.substring(8, 10) + '-' + idCard.substring(10, 12);
}
else if (idCard.length === 18) {
return idCard.substr(6, 4) + "-" + idCard.substr(10, 2) + "-" + idCard.substr(12, 2);
}
return birthdayValue;
}
// 根据身份证号获取年龄
GetAge(idCard) {
if (!idCard) {
return;
}
const birthDay = this.GetBirthday(idCard);
if (birthDay == null || birthDay === "") {
return -1;
}
const birthDate = new Date(birthDay.replace(/-/g, "/"));
const nowDate = new Date();
let age = nowDate.getFullYear() - birthDate.getFullYear();
// 再考虑月、天的因素
if (nowDate.getMonth() < birthDate.getMonth() || (nowDate.getMonth() === birthDate.getMonth()
&& nowDate.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
// 根据身份证号返回与当前语言对应的男、女字符串
GetSex(idCard) {
if (this.IsIDcard(idCard) === false) {
return null;
}
let strSex = "";
// 处理18位的身份证号码从号码中得到生日和性别代码
if (idCard.length === 18) {
strSex = idCard.substring(14, 17);
}
else if (idCard.length === 15) {
strSex = idCard.substring(12, 15);
}
// 性别代码为偶数是女性奇数为男性
if (Number(strSex) % 2 === 0) {
strSex = "女";
}
else {
strSex = "男";
}
return strSex;
}
// 验证身份证号.
IsIDcard(idcard) {
const regularExpression = /(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$)|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3})/;
return regularExpression.test(idcard);
}
/**
* 日期型函数******************************************************************************************************
*/
// 增加指定的天数
DateTimeAddDays(date, value) {
if (!date) {
return date;
}
const tempDate = new Date(date.replace(/-/g, "/"));
tempDate.setDate(tempDate.getDate() + value);
return tempDate;
}
// 增加指定的月数
DateTimeAddMonths(date, value) {
if (!date) {
return date;
}
const tempDate = new Date(date.replace(/-/g, "/"));
tempDate.setMonth(tempDate.getMonth() + value);
return tempDate;
}
// 增加指定的年数
DateTimeAddYears(date, value) {
if (!date) {
return date;
}
const tempDate = new Date(date.replace(/-/g, "/"));
tempDate.setFullYear(tempDate.getFullYear() + value);
return tempDate;
}
// 取指定日期时间值所在月的第一天
GetFirstDayOfMonth(date) {
if (!date) {
return date;
}
const tempDate = new Date(date.replace(/-/g, "/"));
tempDate.setDate(1);
tempDate.setHours(0, 0, 0, 0);
return this.FormatDefineDate('yyyy-MM-dd', tempDate);
}
// 获取指定日期时间值所在月的最后一天
GetLastDayOfMonth(date) {
if (!date) {
return date;
}
const endDate = new Date(date.replace(/-/g, "/"));
// 把日期字符串转换成日期格式
let month = endDate.getMonth();
const nextMonth = ++month;
const nextMonthFirstDay = new Date(endDate.getFullYear(), nextMonth, 1);
const oneDay = 1000 * 60 * 60 * 24;
return this.FormatDefineDate('yyyy-MM-dd', new Date(Number(nextMonthFirstDay) - oneDay));
}
// 获取当前日期时间
GetDateTimeNow() {
// return new Date(); //把日期字符串转换成日期格式
return this.FormatDate('yyyy-MM-dd HH:mm:ss');
}
// 比较2个时间
CompareDate(str1, str2) {
if (!str1 || !str2) {
return;
}
const tempDate1 = new Date(str1.replace(/-/g, "/"));
// 把日期字符串转换成日期格式
const tempDate2 = new Date(str2.replace(/-/g, "/"));
if (tempDate1.getTime() > tempDate2.getTime()) {
return 1;
}
if (tempDate1.getTime() === tempDate2.getTime()) {
return 0;
}
if (tempDate1.getTime() < tempDate2.getTime()) {
return -1;
}
}
// 格式化当前日期
FormatDate(format) {
format = format || 'yyyy-MM-dd';
return this.FormatDefineDate(format, new Date()); // 把日期字符串转换成日期格式
}
// 格式化指定日期
FormatDefineDate(format, datesStr = null) {
let dates;
if (!datesStr) {
dates = new Date(); // 把日期字符串转换成日期格式
}
else if (typeof datesStr === 'string') {
dates = new Date(datesStr.replace(/-/g, "/")); // 把日期字符串转换成日期格式
}
else if (Object.prototype.toString.call(datesStr) === '[object Date]') {
dates = datesStr;
}
else {
console.error('日期参数仅支持日期字符串或日期对象');
return null;
}
const o = {
"M+": dates.getMonth() + 1,
// 月份
"d+": dates.getDate(),
// 日
"H+": dates.getHours(),
// 小时
"m+": dates.getMinutes(),
// 分
"s+": dates.getSeconds(),
// 秒
"q+": Math.floor((dates.getMonth() + 3) / 3),
// 季度
"S": dates.getMilliseconds() // 毫秒
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (dates.getFullYear() + "").substr(4 - RegExp.$1.length));
}
Object.keys(o).forEach((key) => {
if (new RegExp("(" + key + ")").test(format)) {
const value = o[key];
format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? value.toString() : (("00" + value).substr(("" + value).length)));
}
});
return format;
}
// 今天
Today(date = null) {
if (!date) {
const day2 = new Date();
return this.FormatDefineDate('yyyy-MM-dd', day2);
}
const dd = new Date(date);
return this.FormatDefineDate('yyyy-MM-dd', dd);
}
// 昨天
Yesterday(date = null) {
if (!date) {
const day1 = new Date();
day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
return this.FormatDefineDate('yyyy-MM-dd', day1);
}
const dd = new Date(date);
dd.setDate(dd.getDate() - 1);
return this.FormatDefineDate('yyyy-MM-dd', dd);
}
// 明天
Tomorrow(date = null) {
if (!date) {
const dd = new Date();
dd.setDate(dd.getDate() + 1);
return this.FormatDefineDate('yyyy-MM-dd', dd);
}
const dd = new Date(date);
dd.setDate(dd.getDate() + 1);
return this.FormatDefineDate('yyyy-MM-dd', dd);
}
// 本年
ThisYear(date = null) {
if (!date) {
const dd = new Date();
dd.setFullYear(dd.getFullYear());
return dd.getFullYear() + "";
}
const dd = new Date(date);
dd.setFullYear(dd.getFullYear());
return dd.getFullYear() + "";
}
// 去年
LastYear(date = null) {
if (!date) {
const dd = new Date();
dd.setFullYear(dd.getFullYear() - 1);
return dd.getFullYear() + "";
}
const dd = new Date(date);
dd.setFullYear(dd.getFullYear() - 1);
return dd.getFullYear() + "";
}
// 明年
NextYear(date = null) {
let dd = new Date();
if (date) {
dd = new Date(date);
}
return dd.getFullYear() + 1 + '';
}
// 本月
ThisMonth(date = null) {
let dd = new Date();
if (date) {
dd = new Date(date);
}
return dd.getMonth() + 1 + '';
}
// 上月
LastMonth(date = null) {
let dd = new Date();
if (date) {
dd = new Date(date);
}
const currentMonth = dd.getMonth() + 1;
let lastMonth = currentMonth - 1;
if (currentMonth === 1) {
lastMonth = 12;
}
return lastMonth.toString();
}
// 下月
NextMonth(date = null) {
let dd = new Date();
if (date) {
dd = new Date(date);
}
const currentMonth = dd.getMonth() + 1;
let nextMonth = currentMonth + 1;
if (currentMonth === 12) {
nextMonth = 1;
}
return nextMonth.toString();
}
// 星期几
DayOfWeek(date = null) {
let dd = new Date();
if (date) {
dd = new Date(date);
}
return dd.getDay().toString();
}
isLeapYear(year) {
return (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0);
}
getMonthDays(year, month) {
if (typeof month === 'string') {
month = parseInt(month, 10);
}
return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (this.isLeapYear(year) ? 29 : 28);
}
// 本周是第几周
ThisWeek(date = null) {
let dd;
let year;
let month;
let days;
if (!date) {
dd = new Date();
year = dd.getFullYear();
month = dd.getMonth();
days = dd.getDate();
}
else {
dd = new Date(date);
year = dd.getFullYear();
month = dd.getMonth();
days = dd.getDate();
}
const timestamp = dd.getTime();
// 创建一个新的日期对象,表示当前年的第一天
const firstDayOfYear = new Date(year, 0, 1);
// 计算第一天是星期几
const firstDayOfWeek = firstDayOfYear.getDay();
// 计算第一周的起始时间戳
const firstWeekStart = firstDayOfYear.getTime() - (firstDayOfWeek * 24 * 60 * 60 * 1000);
// 计算给定日期距离第一周起始时间的天数
const daysSinceFirstWeekStart = Math.floor((timestamp - firstWeekStart) / (24 * 60 * 60 * 1000));
// 计算周数
const weekNumber = Math.ceil((daysSinceFirstWeekStart + 1) / 7);
return weekNumber;
}
// 上周
LastWeek(date = null) {
return (Number(this.ThisWeek(date)) - 1) + "";
}
// 下周
NextWeek(date = null) {
return (Number(this.ThisWeek(date)) + 1) + "";
}
// 本周第一天
FirstDayOfWeek(date = null) {
if (!date) {
const currentDate = new Date();
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周一
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
return this.FormatDefineDate('yyyy-MM-dd', monday);
}
const currentDate = new Date(date);
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周一
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
return this.FormatDefineDate('yyyy-MM-dd', monday);
}
// 本周最后一天
LastDayOfWeek(date = null) {
if (!date) {
const currentDate = new Date();
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周日
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
const sunday = new Date(monday.getTime() + (6 * millisecond));
// 返回
return this.FormatDefineDate('yyyy-MM-dd', sunday);
}
const currentDate = new Date(date);
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周日
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
const sunday = new Date(monday.getTime() + (6 * millisecond));
// 返回
return this.FormatDefineDate('yyyy-MM-dd', sunday);
}
// 上周第一天
FirstDayOfLastWeek(date = null) {
if (!date) {
const currentDate = new Date();
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周一
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
monday.setDate(monday.getDate() - 7);
return this.FormatDefineDate('yyyy-MM-dd', monday);
}
const currentDate = new Date(date);
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周一
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
monday.setDate(monday.getDate() - 7);
return this.FormatDefineDate('yyyy-MM-dd', monday);
}
// 上周最后一天
LastDayOfLastWeek(date = null) {
if (!date) {
const currentDate = new Date();
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周日
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
const sunday = new Date(monday.getTime() + (6 * millisecond));
sunday.setDate(sunday.getDate() - 7);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', sunday);
}
const currentDate = new Date(date);
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周日
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
const sunday = new Date(monday.getTime() + (6 * millisecond));
sunday.setDate(sunday.getDate() - 7);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', sunday);
}
// 下周第一天
FirstDayOfNextWeek(date = null) {
if (!date) {
const currentDate = new Date();
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周一
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
monday.setDate(monday.getDate() + 7);
return this.FormatDefineDate('yyyy-MM-dd', monday);
}
const currentDate = new Date(date);
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周一
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
monday.setDate(monday.getDate() + 7);
return this.FormatDefineDate('yyyy-MM-dd', monday);
}
// 下周最后一天
LastDayOfNextWeek(date = null) {
if (!date) {
const currentDate = new Date();
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周日
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
const sunday = new Date(monday.getTime() + (6 * millisecond));
sunday.setDate(sunday.getDate() + 7);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', sunday);
}
const currentDate = new Date(date);
const week = currentDate.getDay();
// 一天的毫秒数
const millisecond = 1000 * 60 * 60 * 24;
// 减去的天数
const minusDay = week !== 0 ? week - 1 : 6;
// 本周 周日
const monday = new Date(currentDate.getTime() - (minusDay * millisecond));
const sunday = new Date(monday.getTime() + (6 * millisecond));
sunday.setDate(sunday.getDate() + 7);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', sunday);
}
// 本月第一天
FirstDayOfMonth(date = null) {
if (!date) {
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
// 获得当前年份4位年
const currentYear = currentDate.getFullYear();
// 求出本月第一天
const firstDay = new Date(currentYear, currentMonth, 1, 0, 0, 0, 0);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', firstDay);
}
const currentDate = new Date(date);
const currentMonth = currentDate.getMonth();
// 获得当前年份4位年
const currentYear = currentDate.getFullYear();
// 求出本月第一天
const firstDay = new Date(currentYear, currentMonth, 1, 0, 0, 0, 0);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', firstDay);
}
// 本月最后一天
LastDayOfMonth(date = null) {
if (!date) {
const currentDate = new Date();
const fullYear = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
// getMonth 方法返回 0-11,代表1-12月
const endOfMonth = new Date(fullYear, month, 0);
return this.FormatDefineDate('yyyy-MM-dd', endOfMonth);
}
const currentDate = new Date(date);
const fullYear = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
// getMonth 方法返回 0-11,代表1-12月
const endOfMonth = new Date(fullYear, month, 0);
return this.FormatDefineDate('yyyy-MM-dd', endOfMonth);
}
// 上月第一天
FirstDayOfLastMonth(date = null) {
if (!date) {
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
// 获得当前年份4位年
const currentYear = currentDate.getFullYear();
// 求出本月第一天
const firstDay = new Date(currentYear, currentMonth, 1);
firstDay.setMonth(firstDay.getMonth());
// 返回
return this.FormatDefineDate('yyyy-MM-dd', firstDay);
}
const currentDate = new Date(date);
const currentMonth = currentDate.getMonth();
// 获得当前年份4位年
const currentYear = currentDate.getFullYear();
// 求出本月第一天
const firstDay = new Date(currentYear, currentMonth, 1);
firstDay.setMonth(firstDay.getMonth());
// 返回
return this.FormatDefineDate('yyyy-MM-dd', firstDay);
}
// 上月最后一天
LastDayOfLastMonth(date = null) {
if (!date) {
const currentDate = new Date();
const fullYear = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
// getMonth 方法返回 0-11,代表1-12月
const endOfMonth = new Date(fullYear, month, 0);
endOfMonth.setMonth(endOfMonth.getMonth());
return this.FormatDefineDate('yyyy-MM-dd', endOfMonth);
}
const currentDate = new Date(date);
const fullYear = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
// getMonth 方法返回 0-11,代表1-12月
const endOfMonth = new Date(fullYear, month, 0);
endOfMonth.setMonth(endOfMonth.getMonth());
return this.FormatDefineDate('yyyy-MM-dd', endOfMonth);
}
// 下月第一天
FirstDayOfNextMonth(date = null) {
if (!date) {
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
// 获得当前年份4位年
const currentYear = currentDate.getFullYear();
// 求出本月第一天
const firstDay = new Date(currentYear, currentMonth, 1);
firstDay.setMonth(firstDay.getMonth() + 1);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', firstDay);
}
const currentDate = new Date(date);
const currentMonth = currentDate.getMonth();
// 获得当前年份4位年
const currentYear = currentDate.getFullYear();
// 求出本月第一天
const firstDay = new Date(currentYear, currentMonth, 1);
firstDay.setMonth(firstDay.getMonth() + 1);
// 返回
return this.FormatDefineDate('yyyy-MM-dd', firstDay);
}
// 下月最后一天
LastDayOfNextMonth(date = null) {
if (!date) {
const currentDate = new Date();
const fullYear = currentDate.getFullYear();
const month = currentDate.getMonth() + 2;
// getMonth 方法返回 0-11,代表1-12月
const endOfMonth = new Date(fullYear, month, 0);
return this.FormatDefineDate('yyyy-MM-dd', endOfMonth);
}
const currentDate = new Date(date);
const fullYear = currentDate.getFullYear();
const month = currentDate.getMonth() + 2;
// getMonth 方法返回 0-11,代表1-12月
const endOfMonth = new Date(fullYear, month, 0);
return this.FormatDefineDate('yyyy-MM-dd', endOfMonth);
}
// 本年第一天
FirstDayOfYear(date = null) {
if (!date) {
const currentDate = new Date();
currentDate.setDate(1);
currentDate.setMonth(0);
return this.FormatDefineDate('yyyy-MM-dd', currentDate);
}
const currentDate = new Date(date);
currentDate.setDate(1);
currentDate.setMonth(0);
return this.FormatDefineDate('yyyy-MM-dd', currentDate);
}
// 本年最后一天
LastDayOfYear(date = null) {
let dd = new Date();
if (date) {
dd = new Date(date);
}
const currentDate = dd;
const nextYear = currentDate.getFullYear() + 1;
const nextDate = new Date(nextYear, 0, 1, 0, 0, 0, 0);
const lastDay = nextDate.getTime() - 24 * 3600 * 1000;
return this.FormatDefineDate('yyyy-MM-dd', new Date(lastDay));
}
// 上年第一天
FirstDayOfLastYear(date = null) {
let currentDate = new Date();
if (date) {
currentDate = new Date(date);
}
currentDate.setFullYear(currentDate.getFullYear() - 1);
currentDate.setDate(1);
currentDate.setMonth(0);
return this.FormatDefineDate('yyyy-MM-dd', currentDate);
}
// 上年最后一天
LastDayOfLastYear(date = null) {
let currentDate = new Date();
if (date) {
currentDate = new Date(date);
}
const currentYear = currentDate.getFullYear();
const firstDayOfThisYear = new Date(currentYear, 0, 1, 0, 0, 0, 0);
const lastDayOfLastYear = firstDayOfThisYear.getTime() - 24 * 3600 * 1000;
return this.FormatDefineDate('yyyy-MM-dd', new Date(lastDayOfLastYear));
}
// 下年第一天
FirstDayOfNextYear(date = null) {
let currentDate = new Date();
if (date) {
currentDate = new Date(date);
}
currentDate.setFullYear(currentDate.getFullYear() + 1);
currentDate.setDate(1);
currentDate.setMonth(0);
return this.FormatDefineDate('yyyy-MM-dd', currentDate);
}
// 下年最后一天
LastDayOfNextYear(date = null) {
let currentDate = new Date();
if (date) {
currentDate = new Date(date);
}
const nextNextYear = new Date(currentDate.getFullYear() + 2, 0, 1, 0, 0, 0, 0);
const lastDayOfNextYearTime = nextNextYear.getTime() - 24 * 3600 * 1000;
return this.FormatDefineDate('yyyy-MM-dd', new Date(lastDayOfNextYearTime));
}
// 根据指定日期获取格式化的内容
GetDate(format, date = null) {
switch (format) {
case "DD":
return this.Today(date);
case "LD":
return this.Yesterday(date);
case "ND":
return this.Tomorrow(date);
case "YY":
return this.ThisYear(date);
case "LY":
return this.LastYear(date);
case "NY":
return this.NextYear(date);
case "MM":
return this.ThisMonth(date);
case "LM":
return this.LastMonth(date);
case "NM":
return this.NextMonth(date);
case "WD":
return this.DayOfWeek(date);
case "WW":
return this.ThisWeek(date);
case "LW":
return this.LastWeek(date);
case "NW":
return this.NextWeek(date);
case "FDW":
return this.FirstDayOfWeek(date);
case "LDW":
return this.LastDayOfWeek(date);
case "FDLW":
return this.FirstDayOfLastWeek(date);
case "LDLW":
return this.LastDayOfLastWeek(date);
case "FDNW":
return this.FirstDayOfNextWeek(date);
case "LDNW":
return this.LastDayOfNextWeek(date);
case "FDM":
return this.FirstDayOfMonth(date);
case "LDM":
return this.LastDayOfMonth(date);
case "FDLM":
return this.FirstDayOfLastMonth(date);
case "LDLM":
return this.LastDayOfLastMonth(date);
case "FDNM":
return this.FirstDayOfNextMonth(date);
case "LDNM":
return this.LastDayOfNextMonth(date);
case "FDY":
return this.FirstDayOfYear(date);
case "LDY":
return this.LastDayOfYear(date);
case "FDLY":
return this.FirstDayOfLastYear(date);
case "LDLY":
return this.LastDayOfLastYear(date);
case "FDNY":
return this.FirstDayOfNextYear(date);
case "LDNY":
return this.LastDayOfNextYear(date);
default:
return (date);
}
}
/**
* 计算日期2与日期1直接相差的天数
* @param date1 日期1
* @param date2 日期2
* @description 当两个日期中有一个为空时,则不计算,返回null。
* 该函数是时间差中的一个实现,只返回差的天数,如果差的天数不足一天,则返回0
*/
DayDifference(date1, date2) {
if (!date1 || !date2) {
return null; // If either date is missing, return null
}
date1 = date1.replace(/-/g, "/");
date2 = date2.replace(/-/g, "/");
const dateTime1 = new Date(date1);
const dateTime2 = new Date(date2);
if (!this.isValidDate(dateTime1) || !this.isValidDate(dateTime2)) {
return null; // If either date is invalid, return null
}
const days = parseInt(String((dateTime2.valueOf() - dateTime1.valueOf()) / (24 * 3600 * 1000)));
return days;
}
// List中是否存在等于字符串
IsExistRecord(chainedPropName, propertyName, matchValue) {
return this.eval(`
var list = ${chainedPropName};
var array = DefaultFunction.getIterable(list);
return array