您的位置:首页 > Web前端 > JavaScript

JS设置默认时间范围

2017-06-02 17:04 591 查看
说明:在web开发中,不可避免的会做查询页面和统计页面,两种页面都可能要设置默认统计时间范围,这可以通过JS来实现,代码如下:

var timeModule = ( function () {

/**

* 设置默认日期范围 (最近7天,如:2017-05-01 至 2017-05-07)

* */

initDateTime: function() {

var nowTime = new Date();

var d = nowTime.getDate();

var h = nowTime.getHours();

var m = nowTime.getMinutes();

var s = nowTime.getSeconds();

var initStartDate = new Date(nowTime.getTime() - 6*24*3600*1000 - (h*3600 + m*60 + s)*1000); //获取7天前的开始时间

var initEndDate = nowTime.Format(“yyyy-MM-dd”); //将当前时间格式化

…….. //设置开始日期、结束日期

},

/**

* 设置默认月份范围 (最近半年,如 2017-01 至 2017-06)

* */

initMonthTime: function() {

var nowTime = new Date();

var y= nowTime.getFullYear();

var initStartMonth = new Date(y, nowTime.getMonth()-4, 0).Format(“yyyy-MM”); //获取6个月前的开始月份

var initEndMonth = nowTime.Format(“yyyy-MM”); //将当前时间格式化

…….. //设置开始月份、结束月份

},

/**

* 设置默认年份范围 (最近5年,如 2013 至 2017)

* */

initYearTime: function() {

var nowTime = new Date();

var y= nowTime.getFullYear();

var initStartMonth = “” + y-4 + “”; //获取6个月前的开始月份

var initEndMonth = nowTime.Format(“yyyy”); //将当前时间格式化

…….. //设置开始月份、结束月份

}

})();

/[b]**********************[/b]日期格式化工具[b]*****************************[/b]/

Date.prototype.Format = function (fmt) { //author: meizz

var o = {

“M+”: this.getMonth() + 1, //月份

“d+”: this.getDate(), //日

“h+”: this.getHours(), //小时

“m+”: this.getMinutes(), //分

“s+”: this.getSeconds(), //秒

“q+”: Math.floor((this.getMonth() + 3) / 3), //季度

“S”: this.getMilliseconds() //毫秒

};

if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.1.length));

for (var k in o)

if (new RegExp(“(” + k + “)”).test(fmt)) fmt = fmt.replace(RegExp.1.length == 1) ? (o[k]) : ((“00” + o[k]).substr((“” + o[k]).length)));

return fmt;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 默认时间