Blame view

天文台pc/tianwentai-ui/node_modules/date-fns/setMonth.mjs 1.32 KB
bc518174   王天杨   提交两个项目文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  import { constructFrom } from "./constructFrom.mjs";
  import { getDaysInMonth } from "./getDaysInMonth.mjs";
  import { toDate } from "./toDate.mjs";
  
  /**
   * @name setMonth
   * @category Month Helpers
   * @summary Set the month to the given date.
   *
   * @description
   * Set the month 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 month - The month index to set (0-11)
   *
   * @returns The new date with the month set
   *
   * @example
   * // Set February to 1 September 2014:
   * const result = setMonth(new Date(2014, 8, 1), 1)
   * //=> Sat Feb 01 2014 00:00:00
   */
  export function setMonth(date, month) {
    const _date = toDate(date);
    const year = _date.getFullYear();
    const day = _date.getDate();
  
    const dateWithDesiredMonth = constructFrom(date, 0);
    dateWithDesiredMonth.setFullYear(year, month, 15);
    dateWithDesiredMonth.setHours(0, 0, 0, 0);
    const daysInMonth = getDaysInMonth(dateWithDesiredMonth);
    // Set the last day of the new month
    // if the original date was the last day of the longer month
    _date.setMonth(month, Math.min(day, daysInMonth));
    return _date;
  }
  
  // Fallback for modularized imports:
  export default setMonth;