# moment

# 1. 介绍

# 2. 使用

引入:

import moment from 'moment';

// or
// const moment = require('moment');

解析:

const now = moment();

// moment(str, format)
moment("2023-04-05 13:48:14", 'YYYY-MM-DD HH:mm:ss');

格式化:

moment().format('YYYY-MM-DD HH:mm:ss') // "2023-04-05 13:48:14"

加:

/*
years	    y
quarters	Q
months	  M
weeks	    w
days	    d
hours	    h
minutes	  m
seconds	  s
milliseconds	ms
*/

const now = moment();


/*
moment().add(Number, String);
moment().add(Object);
*/

now.add(7, 'days').add(1, 'months'); // with chaining
now.add({days:7,months:1}); // with object literal

减:

/*
moment().subtract(Number, String);
moment().subtract(Object);
*/

第一(月/日/时/分/秒):

/*
moment().startOf(String);
*/


moment().startOf('year');    // set to January 1st, 12:00 am this year
moment().startOf('month');   // set to the first of this month, 12:00 am
moment().startOf('day');     // set to 12:00 am today
moment().startOf('hour');    // set to now, but with 0 mins, 0 secs, and 0 ms
moment().startOf('minute');  // set to now, but with 0 seconds and 0 milliseconds
moment().startOf('second');  // same as moment().milliseconds(0);

moment().startOf('quarter');  // set to the beginning of the current quarter, 1st day of months, 12:00 am
moment().startOf('week');    // set to the first day of this week, 12:00 am
moment().startOf('isoWeek'); // set to the first day of this week according to ISO 8601, 12:00 am
moment().startOf('date');     // set to 12:00 am today


const formatter = 'YYYY-MM-DD HH:mm:ss';

console.log( moment().format(formatter) );

// 当年 第一月
console.log( moment().startOf('year').format(formatter), 'year' );

// 当月 第一天
console.log( moment().startOf('month').format(formatter), 'month' );
console.log( moment().startOf('day').format(formatter), 'day' );
console.log( moment().startOf('hour').format(formatter), 'hour' );
console.log( moment().startOf('minute').format(formatter), 'minute' );
console.log( moment().startOf('second').format(formatter), 'second' );

最后一(月/日/时/分/秒):

/*
moment().endOf(String);
*/
本章目录