JS时间操作大全
1、获取每个月的开始和结束。
2、获取每个季度的开始和结束。
3、获取当前季度。
4、把日期转换为字符串(支持各种格式)
...
5、未完待续,不断添加
String.prototype.padingStar=function(totalLength,padingStr="") {
if (totalLength <= this.length) {
return this;
}
var padLength = totalLength - this.length;
if (padLength <= padingStr.length) {
return padingStr.substring(0, padLength) + this;
} else {
var len = padLength / padingStr.length, n = 1,str='';
while (n<len) {
str += padingStr;
n++;
}
return str + padingStr.substring(0, padLength - (n-1) * padingStr.length) +this;
}
}
String.prototype.padingEnd = function (totalLength, padingStr="") {
//在开始的补全后面
if (totalLength <= this.length) {
return this;
}
var padLength = totalLength - this.length;
if (padLength <= padingStr.length) {
return padingStr.substring(0, padLength) + this;
} else {
var len = padLength / padingStr.length, n = 0,str='';
while (n<len) {
str += padingStr;
n++;
}
return this + padingStr.substring(0, padLength - (n - 1) * padingStr.length)+str;
}
}
//获取当前月的开始
Date.prototype.starOfMonth=function() {
return new Date(this.getFullYear(), this.getMonth(), 1, 00, 00, 00);
}
//获取当前月的结束
Date.prototype.endOfMonth=function() {
return new Date(this.getFullYear(), this.getMonth() + 1, 0, 23, 59, 59);
}
//获取当前季度的开始时间
Date.prototype.starofQuarter=function() {
return new Date(this.getFullYear(), (this.getQuarter() - 1) * 3, 01, 00, 00, 00);
}
//获取当前季度的结束时间
Date.prototype.endofQuarter=function() {
return new Date(this.getFullYear(), this.getQuarter() * 3-1 , 31, 23, 59, 59);
}
//获取当前时间对应的季度
Date.prototype.getQuarter=function() {
return Math.ceil((this.getMonth() + 1) / 3);
}
//获取当前时间对应的年的开始
Date.prototype.starOfYear=function() {
return new Date(this.getFullYear(), 01, 01, 00, 00, 00);
}
//获取当前时间对应年的结束
Date.prototype.endOfYear=function() {
return new Date(this.getFullYear(), 12, 31, 23, 59, 59);
}
//把时间格式化为字符串
Date.prototype.toDateString = function(format) {
if (typeof (format) == "undefined") {
return this.toString();
}
//可能我的第一个想法,就是
if (/y{4}/.test(format)) {
format = format.replace(/yyyy/g, this.getFullYear());
}
if (/y{2}/.test(format)) {
format = format.replace(/y{2}/g,this.getFullYear().toString().substr(2));
}
if (/M{2}/.test(format)) {
format = format.replace(/MM/,this.getMonth().toString().padingStar(2,0));
}
if (/dd/.test(format)) {
format = format.replace(/dd/,this.getDate().toString().padingStar(2,'0'));
}
if (/HH/.test(format)) {
format = format.replace(/HH/g, this.getHours().toString().padingStar(2, '0'));
}
if (/hh/.test(format)) {
format = format.replace(/hh/g, (hour < 12 ? hour : hour - 12).toString().padingStar(2, '0'));
}
if (/mm/.test(format)) {
format = format.replace(/mm/g, this.getMinutes().toString().padStart(2, '0'));
}
if (/ss/.test(format)) {
format = format.replace(/ss/g, this.getSeconds().toString().padStart(2, '0'));
}
return format;
}
//获取两个时间相隔的天数
Date.prototype.betweenDays=function(date) {
var daySpan = (Date.parse(this) - Date.parse(date)) / 86400000;
return daySpan;
}
github地址:https://github.com/gdoujkzz/JsDate.git