60 lines
1.7 KiB
JavaScript
60 lines
1.7 KiB
JavaScript
|
"use strict";
|
||
|
exports.setDay = setDay;
|
||
|
var _index = require("./addDays.js");
|
||
|
var _index2 = require("./toDate.js");
|
||
|
|
||
|
var _index3 = require("./_lib/defaultOptions.js");
|
||
|
|
||
|
/**
|
||
|
* The {@link setDay} function options.
|
||
|
*/
|
||
|
|
||
|
/**
|
||
|
* @name setDay
|
||
|
* @category Weekday Helpers
|
||
|
* @summary Set the day of the week to the given date.
|
||
|
*
|
||
|
* @description
|
||
|
* Set the day of the week to the given date.
|
||
|
*
|
||
|
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
|
||
|
*
|
||
|
* @param date - The date to be changed
|
||
|
* @param day - The day of the week of the new date
|
||
|
* @param options - An object with options.
|
||
|
*
|
||
|
* @returns The new date with the day of the week set
|
||
|
*
|
||
|
* @example
|
||
|
* // Set week day to Sunday, with the default weekStartsOn of Sunday:
|
||
|
* const result = setDay(new Date(2014, 8, 1), 0)
|
||
|
* //=> Sun Aug 31 2014 00:00:00
|
||
|
*
|
||
|
* @example
|
||
|
* // Set week day to Sunday, with a weekStartsOn of Monday:
|
||
|
* const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
|
||
|
* //=> Sun Sep 07 2014 00:00:00
|
||
|
*/
|
||
|
function setDay(date, day, options) {
|
||
|
const defaultOptions = (0, _index3.getDefaultOptions)();
|
||
|
const weekStartsOn =
|
||
|
options?.weekStartsOn ??
|
||
|
options?.locale?.options?.weekStartsOn ??
|
||
|
defaultOptions.weekStartsOn ??
|
||
|
defaultOptions.locale?.options?.weekStartsOn ??
|
||
|
0;
|
||
|
|
||
|
const _date = (0, _index2.toDate)(date);
|
||
|
const currentDay = _date.getDay();
|
||
|
|
||
|
const remainder = day % 7;
|
||
|
const dayIndex = (remainder + 7) % 7;
|
||
|
|
||
|
const delta = 7 - weekStartsOn;
|
||
|
const diff =
|
||
|
day < 0 || day > 6
|
||
|
? day - ((currentDay + delta) % 7)
|
||
|
: ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);
|
||
|
return (0, _index.addDays)(_date, diff);
|
||
|
}
|