出售域名 11365.com.cn
有需要请联系 16826375@qq.com
在手机上浏览
在手机上浏览

js常用扩展方法

发布日期:2022-09-30

String.prototype.toObject=function(){ //字符串转对象
    return eval('(' this ')');
}
String.prototype.toJSON=function(){ //字符串转JSON对象
    return JSON.parse(this.toString());
}
String.prototype.toDatetime=function(){ //字符串转日期
    return new Date(this);
}
Date.prototype.toFormatDate=function(){ //转日期格式化字符串 如2022-10-01
    return this.toJSON().substring(0,10);
}
Date.prototype.toFormatTime=function(){ //转时间格式化字符串 如10:01:50
    return this.toTimeString().substring(0,8);
}
Date.prototype.toFormatDatetime=function(){ //转日期时间格式化字符串 如12022-10-01 0:01:50
    return this.toFormatDate() ' ' this.toFormatTime();
}

let txt="{username:\"jasonlee\",age:18}";
console.log(txt.toObject());

let txt2="{\"username\":\"jasonlee\",\"age\":18}";
console.log(txt2.toJSON());

let txt3="2022-10-01 10:01:50";
let dt=txt3.toDatetime();
console.log(dt);

console.log(dt.toFormatDate());
console.log(dt.toFormatTime());
console.log(dt.toFormatDatetime());

测试结果:

{username: 'jasonlee', age: 18}
{username: 'jasonlee', age: 18}
Sat Oct 01 2022 10:01:50 GMT 0800 (中国标准时间)
2022-10-01
10:01:50
2022-10-01 10:01:50