Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

74 lines
2.6 KiB

export function isDate(value) {
return value instanceof Date || Object.prototype.toString.call(value) === '[object Date]';
}
export function toDate(value) {
if (isDate(value)) {
return new Date(value.getTime());
}
if (value == null) {
return new Date(NaN);
}
return new Date(value);
}
export function isValidDate(value) {
return isDate(value) && !isNaN(value.getTime());
}
export function startOfWeek(value) {
var firstDayOfWeek = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
if (!(firstDayOfWeek >= 0 && firstDayOfWeek <= 6)) {
throw new RangeError('weekStartsOn must be between 0 and 6');
}
var date = toDate(value);
var day = date.getDay();
var diff = (day + 7 - firstDayOfWeek) % 7;
date.setDate(date.getDate() - diff);
date.setHours(0, 0, 0, 0);
return date;
}
export function startOfWeekYear(value) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$firstDayOfWeek = _ref.firstDayOfWeek,
firstDayOfWeek = _ref$firstDayOfWeek === void 0 ? 0 : _ref$firstDayOfWeek,
_ref$firstWeekContain = _ref.firstWeekContainsDate,
firstWeekContainsDate = _ref$firstWeekContain === void 0 ? 1 : _ref$firstWeekContain;
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError('firstWeekContainsDate must be between 1 and 7');
}
var date = toDate(value);
var year = date.getFullYear();
var firstDateOfFirstWeek = new Date(0);
for (var i = year + 1; i >= year - 1; i--) {
firstDateOfFirstWeek.setFullYear(i, 0, firstWeekContainsDate);
firstDateOfFirstWeek.setHours(0, 0, 0, 0);
firstDateOfFirstWeek = startOfWeek(firstDateOfFirstWeek, firstDayOfWeek);
if (date.getTime() >= firstDateOfFirstWeek.getTime()) {
break;
}
}
return firstDateOfFirstWeek;
}
export function getWeek(value) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$firstDayOfWeek = _ref2.firstDayOfWeek,
firstDayOfWeek = _ref2$firstDayOfWeek === void 0 ? 0 : _ref2$firstDayOfWeek,
_ref2$firstWeekContai = _ref2.firstWeekContainsDate,
firstWeekContainsDate = _ref2$firstWeekContai === void 0 ? 1 : _ref2$firstWeekContai;
var date = toDate(value);
var firstDateOfThisWeek = startOfWeek(date, firstDayOfWeek);
var firstDateOfFirstWeek = startOfWeekYear(date, {
firstDayOfWeek: firstDayOfWeek,
firstWeekContainsDate: firstWeekContainsDate
});
var diff = firstDateOfThisWeek.getTime() - firstDateOfFirstWeek.getTime();
return Math.round(diff / (7 * 24 * 3600 * 1000)) + 1;
}