Date
// 可以获得当前的时间戳
Date.now(); new Date().getTime();
// 将字符串或者时间对象直接转换为时间戳
Date.parse();
// 返回指定对象的原始值获得准确的时间戳值
(new Date()).valueOf();
Moment.js
Moment.js 是一个轻量级的js时间处理类库,其使用简单,方便了日常开发中对时间的操作,提高了开发效率。
常用的方法
1、moment()
- 获取当前的日期和时间:moment()
- 获取String的日期和时间:moment(String)
2、获取 get
- 获取当天的年份:moment().get('year')
- 获取当天的月份(0-11) :moment().get('month')
- 获取当天的日期:moment().get('date')
3、格式 format
得到的时间格式为YYYY-MM-DD:
- moment(String,'YYYY-MM-DD')
- moment(String).format('YYYY-MM-DD')
4、设置 subtract
.subtract(Number, String)
- 设置年份,获取一年前的时间:moment().subtract(1, 'years')
- 设置月份,获取一个月前的时间:moment().subtract(1, 'months')
- 设置日期,获取昨天的时间:moment().subtract(1, 'days')
5、开始 startOf()
.startOf(String):通过将原始的 moment 设置为时间单位的开头来对其进行更改
- 获取今天的0时0分0秒:moment().startOf('day')
- 获取本周第一天的0时0分0秒:moment().startOf('week')
6、结束 endOf()
通过将原始的 moment 设置为时间单位的末尾来对其进行更改
.endOf(String);
获取今天的23时59分59秒:moment().endOf('day')
获取本周第一天的23时59分59秒:moment().endOf('week')
7、总天数 daysInMonth()
获取2012年2月的天数:moment("2012-02", "YYYY-MM").daysInMonth() // 29
8、时间措
.unix() //秒数 .valueOf() //毫秒数
不能选择今天之前的日期(包括今天):
disabledDate(current) {
return current && current < moment().endOf('day');
}
不能选择今天之前的日期(不包括今天):
disabledDate(current) {
return current && current < moment().subtract(1, 'days').endOf('day')
},
点击选择的2019-01-01之前的数据无法确认:
disabledDate(current) {
return current && current < moment('2019-01-01')
}
- 获取时间戳(以秒为单位):moment().format('X').unix() // 返回值为数值型
- 获取时间戳(以毫秒为单位):moment().format('x').valueOf() // 返回值为数值型