Moment.js Cheat Sheet

Now

  • moment();
  • moment().format();
  • moment().format("YYYY/MM/DD HH:mm:ss dddd");
  • moment().format("MMMM Do YYYY, h:mm:ss a");
  • moment().format("[今天是] YYYY [年中的第] DDD [天]");

String

  • moment("12/25/1995", "MM-DD-YYYY");
  • moment("12/25/1995", "MM-DD-YYYY").format();
  • moment("12/25/1995", "MM-DD-YYYY").format("YY Mo DD ddd");

Unix Timestamp

  • moment(1565445319797);
  • moment(1565445319797).format();
  • moment(1565445319797).format("YYYY-MM-DD HH:mm:ss");
  • moment().valueOf(); //milliseconds
  • moment().unix(); //seconds

UTC

  • moment.utc();
  • moment.utc().format();
  • moment.utc("2019-08-10T17:32:22Z");
  • moment.utc("2019-08-10T17:32:22Z").format();
  • moment.utc("2019-08-10T17:32:22Z").format("YYYY MMMM Do");
  • moment.utc(1565445319797);
  • moment.utc(1565445319797).format();

Time from now

  • moment([1990,0,1]).fromNow();
  • moment([1990, 0, 1]).fromNow(true);
  • moment("20120620", "YYYYMMDD").fromNow();

Time from X

  • var a = moment([2007,0,28]);

    var b = moment([2007,0,29]);

    a.from(b);

Time to now

  • moment([1990, 0, 1]).toNow();
  • moment([1990, 0, 1]).toNow(true);
  • moment("20120620", "YYYYMMDD").toNow();

Time to X

  • var a = moment([2007,0,28]);

    var b = moment([2007,0,29]);

    a.to(b);

Calendar Time

  • moment().calendar();
  • moment([2019,0,1]).calendar();

Difference

  • var a = moment([2007,0,28]);

    var b = moment([2007,0,27]);

    a.diff(b);

  • var a = moment([2007,0,28]);

    var b = moment([2007,0,27]);

    a.diff(b,"days");

Days in Month

  • moment().daysInMonth();
  • moment("2012-02", "YYYY-MM").daysInMonth();

As JavaScript Date

  • moment().toDate();

As Array

  • moment().toArray();

As JSON

  • moment().toJSON();

As String

  • moment().toString();

Is Before

  • moment().isBefore('2010-10-21');
  • moment('2010-10-20').isBefore('2010-10-21');

Is After

  • moment().isAfter('2010-10-21');
  • moment('2010-10-20').isAfter('2010-10-21');

Is Between

  • moment('2010-10-20').isBetween('2010-10-19', '2010-10-25');
  • moment('2010-10-20').isBetween('2010-10-19', undefined);