yearMonth()
yearMonth(input, options?): YearMonth
yearMonth(input, zone?): YearMonth
yearMonth(year, month): YearMonth从年份在前的字符串、年份与从 1 开始计数的月份数字、字段对象,或任意日期与时间戳创建 YearMonth(传入日期或时间戳时自动舍弃日字段)。缺少输入时会抛出 TypeError,不会默认取当前月份。
import { datetime, yearMonth } from 'native-dates';
const fromIso = yearMonth('2026-11');
const fromNumbers = yearMonth(2026, 11);
const fromFields = yearMonth({ year: 2026, month: 11 });
const fromDate = yearMonth('2026-11-16');
const fromInstant = yearMonth(datetime('2026-11-01T02:00:00Z'), 'America/Los_Angeles');
fromNumbers.toString(); // '2026-11'
fromInstant.toString(); // '2026-10'参数
ISO 年月字符串、字段对象、日期或时间戳,或日历年份 year。
解析时间戳或宽松字符串时的时区或选项对象,或从 1 开始计数的月份 month(1 到 12)。
3 个选项
用于确定时间戳字符串、DateTime 或 Date 对应当地日历月份的时区。
绑定到返回的 YearMonth 及其后续所有派生值的 BCP 47 区域标签。
false配合 @native-dates/plugins/loose 解析英文或本地化月份名(如 'février 2026'),无法解析时返回 null。
返回值
不含日字段的 YearMonth 实例;宽松模式下无法解析 input 时返回 null。
加载 loose 插件后,宽松模式可以解析英文或当前 locale 下的月份名搭配 4 位年份,无法解析时返回 null:
import { yearMonth } from 'native-dates';
import '@native-dates/plugins/loose';
yearMonth('Nov 2026', { loose: true })?.toString(); // '2026-11'
yearMonth('février 2026', { loose: true, locale: 'fr' })?.toString(); // '2026-02'
yearMonth('not-a-month', { loose: true }); // null