moment.js 在工作中的一些应用总结

399 阅读2分钟

在公司写项目过程中经常用会到moment.js。为了提升工作效率,对常见用法做了一些梳理。

moment.js用法

  1. 格式化为 标准时间

时间分别是: 年:YYYY
月:MM
日: DD
星期:dddd

moment().format()
moment().format("YYYY MM DD dddd");
  1. 格式化为 时间戳
moment( ).valueOf()
  1. 获取某个moment时间的年、月、日、时、分、秒、毫秒
moment().toArray()
  1. 获取某天的开头和结尾
moment().startOf('day')
moment().endOf('day')
  1. 获取某个月份的开头和结尾
moment().startOf('month').format(); // 2022-03-01T00:00:00+08:00
moment().endOf('month').format(); // 2022-03-31T23:59:59+08:00
  1. 获取当月、2022年 4月,芝加哥时间的开始和结束 涉及到不同时区的时间时,用的是moment-timezone.js 插件。moment-timezone中也实现了moment的各种属性和方法。它主要使用moment.tz( ) 方法,来将当地时间转化为某个时区的时间。
// 当月,芝加哥时间的开始和结束
const chicagoTime = moment
    .tz(time.toArray(), "America/chicago")
    .startOf("month")
    .format();
  const chicagoTime1 = moment
    .tz(time.toArray(), "America/chicago")
    .endOf("month")
    .format();
// 2022-03-01T00:00:00-06:00 2022-03-31T23:59:59-05:00

// 2022年4月,芝加哥开始和结束时间
const chicagoTime3 = moment
    .tz([2022, 3], "America/chicago")
    .startOf("month")
    .format();
  const chicagoTime4 = moment
    .tz([2022, 3], "America/chicago")
    .endOf("month")
    .format();
// 2022-04-01T00:00:00-05:00 2022-04-30T23:59:59-05:00
  1. 某一天是否在另一天之前
moment().isBefore('2022-03-07')   // true
  1. 某一天 往前推算30天第0秒; 往后推算30天第23:59:59;如果是1号,找到本月最后一秒
// 往前推算30天第0秒
moment().subtract(30, 'day').startOf('day')

// 往后推算30天第23:59:59
moment().add(30, 'day').endOf('day')
  1. 克隆当前选择的这一天
const origin = moment()
const cloneDate = origin.clone()
cloneDate.year(2000)
  1. 今天是当年的第多少天
moment().format("DDDD");