Welcome to new things

[Technical] [Electronic work] [Gadget] [Game] memo writing

Memo on how to use Moment.js, a JavaScript date calculation library

When performing date operations in JavaScript, the built-in Date function is difficult to handle, so some kind of library is generally used.

The library uses the commonly seen "Moment.js".

I forget how to use it no matter how many times I do it, and I keep getting stuck in the same place, so I'll leave a note for my own use.

Installation and loading

Since we often use Japan Standard Time (JST), we use moment-timezone to work without setting the server locale.

install

npm install moment-timezone

read in

import * as moment from 'moment-timezone';
moment.tz.setDefault('Asia/Tokyo'); // Set time zone to JST

// TypeScript
// Convenient to specify when passing it as a function argument for completion.
import { Moment } from 'moment-timezone';

// Example of type usage
function test(date: Moment){

}

Generation and output

The set time zone is

  • Date of when to generate" when no offset is specified.
  • Date when output is to be made."

This will affect the

The output will be in the set time zone, but if you want pinpoint UTC output, use moment.utc() to temporarily convert to UTC and output.

import * as moment from 'moment-timezone';
moment.tz.setDefault('Asia/Tokyo'); 

// Get current time
const date_now = moment(); 

// Output will be JST.
date_now.format('YYYY-MM-DD HH:mm:ss');

// Create by specifying all values
// Input values without offset are treated as JST
const date_jst = moment('2019-01-01 00:00:00.000');  

// Full Format Output
// Input values are treated as JST.
date_jst.format('YYYY-MM-DD HH:mm:ss.SSSZ');
// 2019-01-01 00:00:00.000+09:00

// Offset can be specified for input values
// No ms designation is required.
const date_utc = moment('2019-01-01 00:00:00.000+00:00');  

// The input was set to UTC, so the output JST is 9 hours ahead of 9:00.
date_utc.format('YYYY-MM-DD HH:mm:ss.SSSZ');
// 2019-01-01 09:00:00.000+09:00

// Converted to UTC and output
// Since the input was in UTC, the output has the same value.
date_utc.utc().format('YYYY-MM-DD HH:mm:ss.SSSZ');
// 2019-01-01 00:00:00.000+00:00

Generated from special format string

If the date string is not in "YYYYY-MM-DD HH:mm:ss" format, it can be generated by specifying the format in the second argument.

For example, the date obtained from Twitter's API is in the format "Fri Mar 05 14:11:26 +0000 2010", from which moment is generated as follows.

const date_twitter = moment(
    'Fri Mar 05 14:11:26 +0000 2010',
    'ddd MMM DD HH:mm:ss ZZ YYYY'
);
console.log(date_twitter.utc().format('YYYY-MM-DD HH:mm:ss'));
// 2010-03-05 14:11:26

A similar method can be used to generate from unixtime.

The format description is the same as that of the output and is explained in the TOKENS below.

format

Outputs strings in the format specified by moment.format().

It would be good to note the full format for now, and then cut it out and use it as needed.

Creating a moment can be done with a minimum of "date and time" information.

It is recommended that the output be formatted so that the less-than digits are zero-filled and "-" is used between "date" and "year" to facilitate sorting and reduce errors when loading to the database.

const date = moment('2019-01-01');
// full format
datel.format('YYYY-MM-DD HH:mm:ss.SSSZ');
// 2019-01-01 00:00:00.000+09:00

Elements are retrieved and modified via format

moment.~() to get the value." moment.~(<number>) can be used to change the value, but the behavior is peculiar, so I did not use them, It is less error prone to use "format" instead of moment.~(<number>), although it is more time-consuming.

Behavioral quirks

  • moment.month() indicates the month, but the range is 0 to 11, not 1 to 12.
  • The date of the month is moment.date(), not moment.day().

If you know these quirks, there is no problem, but if you haven't used them for a while, you tend to forget about them, so I've decided to split the difference and not use the element get/change functions.

Retrieval and modification via FORMAT

const date = moment('2019-02-03');

// Get
// String output in format and type conversion
Number.parseInt(date.format('M');
// Month: Range "1-12".

// change
// Output String in format and re-create moment with that String.
const date_last_year = moment(date.format('2018-MM-DD'));

Day of the week acquisition

As an exception, moment.isoWeekday() is used to obtain the week.

The numbers "1-7" are for "Monday-Sunday."

const date = moment('2019-01-01');
date.isoWeekday());
// 1 (Monday)

Cautionary note on operations

Moment.js operations are not immutable.

When an object is operated on, the value of the object is changed.

const date_original = moment('2019-01-01');
const date_result = date_original.add(2, 'day');

date_result.format('YYYY-MM-DD'));
// 2019-01-03

date_original.format('YYYY-MM-DD');
// 2019-01-03
// date_original is added.

Because the moment assignment is a copy of a reference, if the copy is changed, the referent is also changed.

const date_original = moment('2019-01-01');
const date_ref = date_original;

date_ref.add(2, 'day');

date_original.format('YYYY-MM-DD');
// 2019-01-03
// date_original is added.

It is better to make a copy of the operation with moment.clone() and use the copy for the operation to avoid mistakes.

const date_original = moment('2019-01-01');

// copyediting
const date_copy = date_original.clone();

// calculation
const date_add = date_copy.add(2, 'day');

date_add.format('YYYY-MM-DD');
// 2019-01-03

date_original.format('YYYY-MM-DD');
// 2019-01-01
// date_original is still original

Units used in arithmetic operations

Key
year
month
day
hour
minute
second
millisecond

Differential (diff)

You can specify the unit of difference.

const date_a = moment('2020-01-01');
const date_b = moment('2019-01-01');

date_a.diff(date_b, 'year');  // a - b
// 1

Additions and subtractions

There is a separate subtraction function, but it can also be done using negative values for addition, which is less complicated to remember.

const date = moment('2019-01-01');

date.add(1, 'day'); // 2019-01-02
date.add(-1, 'day'); // 2018-12-31

Comparison

If the unit is not specified in moment.diff(), the difference is in ms (minimum unit).

This is used to compare moments with each other.

const date_a = moment('2019-01-01');
const date_b = moment('2020-01-01');

if(date_a.diff(date_b)>0){
   // date_a>date_b
}

if(date_a.diff(date_b)<0){
   // date_a<date_b
} 

if(date_a.diff(date_b)===0){
   // date_a=date_b
} 

However, there are times when we do not want to make exact comparisons, such as checking if it is the same day.

Moment.js does not provide a means of truncating such units, so it is better to perform the operation by truncating the unit once to a String with a format.

const date_a = moment('2019-01-01');
const date_b = moment('2020-01-01');
const str_a = date_a.format('YYYY-MM-DD');
const str_b = date_a.format('YYYY-MM-DD');

if(str_a>str_b){
   // date_a>date_b
}

if(str_a<str_b){
   // date_a<date_b
} 

if(str_a===str_b){
   // date_a=date_b
} 

End of month date acquisition

To get the date at the end of the month, you can subtract one day from the beginning of the month, but it is easier to use moment.endOf('month').

However, please note that the time is 12:00 pm.

const date = moment('2019-01-01');

const date_end_of_month = date.endOf('month');
date_end_of_month.format('YYYY-MM-DD hh:mm:ss');
// 2019-01-31 11:59:59 

Impressions, etc.

I often copy and paste the code I use from existing code or write it down in Evernote, but sometimes the process is so abbreviated that a quick glance at the code leaves me wondering, "What was that? I sometimes wonder "what was it?

If I write an article like this, I will also write why it is so, so it will be good for my own use later.

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com