获取每年的第一周
ISO 8601日期表示每年带星期四的一周为第一周,项目需求:根据“YYYY年”,“YYYY年MM月”,“YYYY年IW周”,“YYYY年Q季度”获取起始终止时间。
输入:2015年01周
输出:[“2014-12-29”,”2015-01-04”]
StringToBetweenDate = function(stringDate){
// 日期加减
addDays = function(date, day){
if (date == undefined) date = new Date();
if (day == undefined) day = 0;
var d = date instanceof Date?date:new Date(date);
d.setDate(d.getDate() + day);
return d.format("yyyy-MM-dd");
}
// 字符串合并
join = function(args, sign){
if (args == undefined || args.length < 2) return;
if (sign == undefined) sign = "-";
return args.join(sign);
}
// 每月最后一天
lastDayOfMonth = function(y, m){
var day = new Date(y, m, 0);
return join([y,m,day.getDate()])
}
// 每年第一周第一天 0是周日
fstWeekOfYear = function(y){
var day = new Date(y+"-01-01");
var d = day.getDay()<2?(2-day.getDay()):(9-day.getDay());
return d>4?addDays(join([y,1,d]), -7):join([y,1,d]);
}
var yLen = 4;qLen = 1;mLen = 2;wLen = 2;
var y = stringDate.substr(0, yLen);
switch (true) {
// 季度 2017年1季度
case /\u5b63\u5ea6/.test(stringDate):
var q = stringDate.substr(yLen + 1, qLen);
start = join([y,3*q-2,1]);end = lastDayOfMonth(y,3*q);;
return [start, end];
// 月 2017年02月
case /\u6708/.test(stringDate):
var m = stringDate.substr(yLen + 1, mLen);
start = join([y,m,1]);end = lastDayOfMonth(y,m);
return [start, end];
// 周 2017年09周
case /\u5468/.test(stringDate):
var w = stringDate.substr(yLen + 1, wLen) - 1;
start = addDays(fstWeekOfYear(y), 7*w);end = addDays(start, 6)
return [start, end];
// 年 2017年
case /\u5e74/.test(stringDate):
start = join([y,1,1]);end = lastDayOfMonth(y, 12);
return [start, end];
default:
return ["1970-1-1", addDays()];
}
}