js

一、moment.js

Moment.js是一个轻量级的JavaScript时间库,它方便了日常开发中对时间的操作,提高了开发效率。日常开发中,通常会对时间进行下面这几个操作:比如获取时间,设置时间,格式化时间,比较时间等等。下面就是我对moment.js使用过程中的整理,方便以后查阅。

// require 方式 
var moment = require('moment');

二、设定moment区域在中国

// require 方式
require('moment/locale/zh-cn')
moment.locale('zh-cn'); 

三、使用

1. 获取时间
(1) 获取当前时间
moment()
(2)获取今天0时0分0秒
moment().startOf('day')
(3) 获取本周第一天(周日)0时0分0秒
moment().startOf('week')
(4)获取本周周一0时0分0秒
moment().startOf('isoWeek')
2. 设置时间

1)设置年份

moment().year(2019)
moment().set('year', 2019)
moment().set({year: 2019})

(2)设置月份

moment().month(11)  // (0~11, 0: January, 11: December)
moment().set('month', 11) 

(3)设置某个月中的某一天

moment().date(15)
moment().set('date', 15)

(4)设置某个星期中的某一天

moment().weekday(0) // 设置日期为本周第一天(周日)
moment().isoWeekday(1) // 设置日期为本周周一
moment().set('weekday', 0)
moment().set('isoWeekday', 1)

(5)设置小时

moment().hours(12)
moment().set('hours', 12)

(6)设置分钟

moment().minutes(30)
moment().set('minutes', 30)

(7)设置秒数

moment().seconds(30)
moment().set('seconds', 30)

(8)年份+1

moment().add(1, 'years')
moment().add({years: 1})

(9)月份+1

moment().add(1, 'months')

(10)日期+1

moment().add(1, 'days')

(11)星期+1

moment().add(1, 'weeks')

(12)小时+1

moment().add(1, 'hours')

(13)分钟+1

moment().add(1, 'minutes')

(14)秒数+1

moment().add(1, 'seconds')

(15)年份-1

moment().subtract(1, 'years')
moment().subtract({years: 1})

(16)月份-1

moment().subtract(1, 'months')

(17)日期-1

moment().subtract(1, 'days')

(18)星期-1

moment().subtract(1, 'weeks')

(19)小时-1

moment().subtract(1, 'hours')

(20)分钟-1

moment().subtract(1, 'minutes')

(21)秒数-1

moment().subtract(1, 'seconds')
3. 格式化时间

(1)格式化年月日: ‘xxxx年xx月xx日’

moment().format('YYYY年MM月DD日')

(2)格式化年月日: ‘xxxx-xx-xx’

moment().format('YYYY-MM-DD')

(3)格式化时分秒(24小时制): ‘xx时xx分xx秒’

moment().format('HH时mm分ss秒')

(4)格式化时分秒(12小时制):‘xx:xx:xx am/pm’

moment().format('hh:mm:ss a')

(5)格式化时间戳(以毫秒为单位)

moment().format('x') // 返回值为字符串类型
4. 转化为javascripe原生date对象
moment().toDate() new Date(moment())

学习中,自己总结的常用获取时间的方法,希望对大家有用,谢谢。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐