moment控件常用API详解

moment控件常用API详解

Moment对象获取方式

var day = moment("1995-12-25 10:12:12"); // moment时间对象
moment({y:2010, M:3, d:5, h:15, m:10, s:3, ms:123}); // moment时间对象
moment([2010, 1, 14, 15, 25, 50, 125]); // moment时间对象
moment(1528519053128); // moment时间对象(毫秒时间戳)
moment.unix(1528519053.128);  // moment时间对象(秒时间戳)
moment().add(1, 'day'); // 向后一天的moment时间对象
moment().subtract(1, 'day'); // 向前一天的moment时间对象

判断是不是时间格式

moment("not a real date").isValid(); // 当前字符串是不是时间格式(true or false)

获取时间戳

moment().add(1, 'day').format('YYYY-MM-DD-hh-mm-ss').split('-') // 可以拆分出当前的时间段
moment().format('x');  // 毫秒级时间戳
moment().format('X');  // 秒级时间戳

时间间隔(两个时间戳差值-》换算成时、分、秒等)

moment.duration(1528977631466-1528891135000).milliseconds(); 
其他:
milliseconds();
seconds()
minutes()
hours();
days();
months();
years()

克隆moment()时间

var a = moment([2012]);
var b = a.clone();

转为UTC时间(UTC时区是0时区;中国属于东8区(比0时区向后延8小时))

moment.utc();
moment.utc(Moment);

当前时区

moment.tz.guess();//获取当前时区位置,"Asia/Shanghai"
moment().utcOffset() / 60 ;  //8,代表东八区
moment(1528524631192).tz("America/Toronto").format('Z') // -4:00  代表西4区,与东八区相差12h
moment.tz.names(); // 获得所有时区的地点数组["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", ...]
-------
var zone = "America/Los_Angeles";
moment(1528524631192).tz(zone).format()

取值:

moment().get('year');
moment().get('month');  // 0 to 11
moment().get('date');
moment().get('hour');
moment().get('minute');
moment().get('second');
moment().get('millisecond');
moment().get('day')

也可以使用:(取值、赋值通用)
moment().year()
moment().month()
moment().date()
moment().hour()
moment().minute()
moment().second()
moment().millisecond()
moment().day()

赋值:

moment().set('year', 2013);
moment().set('month', 3);  // April
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);
moment().set('day', 6)

最大值和最小值,开始时间,结束时间:

var a = moment().subtract(1, 'day');
var b = moment().add(1, 'day');
moment.max(a, b);  // b
moment.min(a, b);  // a
moment.startOf('day'); // 当天的开始时间
moment.endOf('day'); // 当天的结束时间

操作:

示例:moment().add(7, 'days').subtract(1, 'months').year(2009).hours(0).minutes(0).seconds(0)

// 操作加法(减法:moment().subtract(1, 'day'))
moment().add(7, 'year')
moment().add(7, 'quarters') // 季度
moment().add(7, 'month')
moment().add(7, 'week') // 周
moment().add(7, 'day')
moment().add(7, 'hour')
moment().add(7, 'minute')
moment().add(7, 'second')
moment().add(7, 'millisecond') // 毫秒

查询相关api

在这里插入图片描述

发布了7 篇原创文章 · 获赞 3 · 访问量 555

猜你喜欢

转载自blog.csdn.net/weixin_44953136/article/details/105298946
今日推荐