moment.js使用详解

总结了关于moment.js库的常见用法,以功能为主线,实现相关代码,备忘备查。

const moment = require("moment");

let time = null;

// 设置全局语言
moment.locale("zh-cn");

// 初始化当下时间
time = moment();
console.log(time);

// 按照格式初始化
time = moment("2000-01-01", "YYYY-MM-DD");
console.log(time);

// 时间戳转化moment
time = moment(1534773314000);
console.log(time);

// moment转化时间戳
time = moment().valueOf();
console.log(time);

// Moment 转化为 Date对象
time = moment()
    .toDate()
    .getTime();
console.log(time);

// 格式化当前时间
time = moment().format("YYYY-MM-DD HH:mm:ss A");
console.log(time);

// 7天前
time = moment().subtract(7, "days"); //Other else: years, months, weeks, hours, minutes, seconds, milliseconds
console.log(time);

// 7天后
time = moment().add(7, "days"); //Other else: years, months, weeks, hours, minutes, seconds, milliseconds
console.log(time);

// 日历时间
time = moment().calendar();
console.log(time);

// 获得时间差
time = moment("2000-01-01", "YYYY-MM-DD").fromtime(true);
console.log(time);

// 获得今天结束时间
time = moment()
    .endOf("minute")
    .toDate(); // Other else: year, day, week, month, hour...
console.log(time);

// 是否Moment对象
console.log(moment.isMoment(new Date()));
console.log(moment.isMoment(moment()));

// 是否Date对象
console.log(moment.isDate(new Date()));
console.log(moment.isDate(moment()));

官网:

详细文档:

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×