Moment.js, A Simple Tool For Calculating Date And Time(feat.Nodejs)

Easy way to calculate date and time way better

Sometimes we need to calculate date and time.

Actually more than sometimes.

And this library, moment.js, is so powerful for your purpose.

Getting date, setting a date format whatsoever you want, subtracting date from date, counting days, and others.

Below listed some functions for your quick use.

Let’s dig it.

Install moment.js

Install library with below command.

npm install moment

Import the library with ‘require’ function.

var moment = require('moment');

//ES6 syntax
import moment from 'moment';

Let’s get started from parsing date.

const date = moment(""); //2022-01-23T11:15:00+09:00

We can display date using format() method with below tokens.

YY(YY) year ex) YYYY -> 2022, YY -> 22
MM(MM) monthex) MMMM -> January, MM -> 01
DD dateex) DD -> 25
dd(dd) dayex) dd -> Tu, dddd -> Tuesday
hhhour(12)ex) hh -> 01
HH hour(24)ex) HH -> 13
mm minuteex) mm -> 07
sssecondex) ss -> 03
a am, pmex) a -> pm
Do ordinalex) Do -> 25th
//January Tu 2022, 01:07:21 pm
moment.format('MMMM dd YYYY, hh:mm:ss a'); 

//January Tuesday 2022, pm 01:17
moment.format('MMMM dddd YYYY, a hh:mm') 

// 01/25/2022

isValid() method works well on it.

moment('2022-01-25','YYYY-MM-DD').isValid(); //true

moment('2022-02-30','YYYY-MM-DD').isValid(); //false

moment('My birth is 2022-1-25','YYYY-MM-DD').isValid(); //true

Also parsing every detail date is available by intuitive methods.

hour()get hour
minute()get minute
second()get second
millisecond()get millisecond
date()get date (1~31)
day()get day of week (0~6)
week()get week of year (1~53)
month()get month (0~11)
year()get year
moment(new Date).hour(); //13

moment().millisecond(); //331

moment().week(); //5

To get the difference in date, use diff() method.

const theDate = moment('2021-01-20', 'YYYY-MM-DD');
const myDate = moment('2022-01-25', 'YYYY-MM-DD');

myDate.diff(theDate, 'days');     // 5
myDate.diff(theDate, 'year');    // 1
myDate.diff(theDate, 'month');  // 12

We can use this method for counting expire date or calculate D-day.

And there is a bunch of methods this library thanks to the last long maintenance till today.

Please check official web for further infomation.

AWS EC2 – From Launch New Instance To Install Everything We Need

Simple Explanation Of Setting up AWS EC2(Ubuntu18.04)

1. Launch New Instance In AWS

On a EC2 Management Console page, launch instances and choose Ubuntu Server 18.04 LTS with adequate instance type.

I chose t2 micro Type and launched.

On the next page, click Edit security groups and open port 22, 80, 443 for the next step.

Before launch the instance, you should select an existing key pair or create a new one.

If you don’t have any, create a new one and download key pair.

You should keep that key pair safe and don’t let be exposed to anyone.

We need an elastic IP address(Non-change address) for our accessibility.

Elastic IP lasts forever even if you stop the instance unless you release the IP address.

EC2 -> Network & Security -> Elastic IPs -> Allocate Elastic IP address.

Associate Elastic IP address and Choose an instance to stick them together.

Half way there.

Now you have your own instance and elastic IP address.

Keep going.

2. Connect To The Server Using SSH Client

You can use any SSH Client whatever you want.

This time I chose XShell7 that is free for Home/School.

Put the IP address in Host textbox.

Go to Authentication, write User Name ‘ubuntu’ and check Method Public Key.

Click Connect.

Browse and select the key pair that we downloaded.

If you get this message, now you are in.

3. Install Nodejs On Ubuntu Server

$ curl -sL | sudo -E bash -

$ sudo apt-get install -y nodejs

Execute line by line and when it’s done, we can check by ‘node -v’ command.

If node version(v14.18.2 or something) is printed, installation is done.

4. Install MongoDB On Ubuntu Server

$ wget -qO - | sudo apt-key add -

If you see ‘OK‘ return with above command, you are ready for the next step.

$ echo "deb [ arch=amd64,arm64 ] bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

If you see ‘echo “deb [ arch=amd64,arm64 ] bionic/mongodb-org/4.4 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list‘, move forward.

$ sudo apt-get update
$ sudo apt-get install -y mongodb-org

If you feel like something goes on a busy process, just wait.

When it’s done, check an installation with this command.

‘mongo -version’

Start mongodb service with this command.

$ sudo service mongod start

When successfully started, no message output.

$ mongo

> use admin

> db.createUser({ user:'id', pwd:'pwd', roles:[{"role":"userAdminAnyDatabase","db":"admin"},{"role":"readWriteAnyDatabase","db":"admin"}]})


Have to change some codes for accessibility and security.

$ sudo vi /etc/mongod.conf

binIp : -> bindIp: ::,

#security -> refer to above capture. no space before ‘enabled’ makes error.

save it!(‘wq’ command)

If you want to give a access try, use Compass with 27017 port opened.

5. Deploy(git clone)

Use Git, clone your project to your instance and install dependencies.

$ git clone

$ cd repo
$ npm install

6. Run Server With PM2

Install pm2 and run your own server.

pm2 makes your server keep running if you close the shell.

$ sudo npm install pm2 -g

$ sudo pm2 start index.js //in my case with arguement -> sudo pm2 start src/index.js --node-args="-r esm"

Now, your server won’t stop unless you stop the PM2.

You can check the PM2 status with below command.

$ sudo pm2 list

7. Install Nginx On Ubuntu Server

Nginx has additional functions that Nodejs do not have.

Simply in two ways, security and load balancing.

$ sudo apt-get install nginx

We opened port 80 for Nginx access.

When Nginx works, clients come in through Nginx door and Nginx leads them to internal port.

$ sudo service nginx start

When Nginx started, access it with your ip address.


Nginx welcomes you if you are on right process.

Now, Change some codes as below with vi editor to complete Nginx work.

$ cd /etc/nginx/sites-enabled

sudo vi default

Comment out try_files $uri $uri/ =404; and add

    proxy_pass http://yourIP:port/;
    proxy_set_header Host $http_host;
    proxy_http_version 1.1;
    proxy_set_header X-Nginx-Proxy true;
    proxy_redirect off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass takes clients to internal port that you set on Nodejs.

In my case,;

Save it.

Next step is set a size limitation.

Nginx’s default file size setting is 1MB.

But if your page handles bigger than 1 MB files upload or download, this setting is necessary.

$ sudo vi /etc/nginx/nginx.conf
client_max_body_size 10M(limit size that you want);

Now, restart Nginx.

sudo service nginx restart

Now you can access you page that you made.

8. SSL certificate with Let’s Encrypt(http ->https)

Using Route53 service, get a own domain and manage DNS.

Redirect to your IP address and when you have your own domain, you can get a SSL certification with Let’s Encrypt for free.

$ sudo add-apt-repository ppa:certbot/certbot

$ sudo apt install python-certbot-nginx

$ sudo certbot --nginx -d

Follow the direction, and then your web can get a SSL certification and https protocol is available.

The direction is simple.

1. enter your email address

2. Agree

3. Yes(or No)

4. choose No.2 (redirect http to https option)

And that’s it.

Important thing for the last step is opening the port 443.

Port 443 is a port for https.

Restart Nginx and access with your domain address.

Automatically https will welcome you.

Every 90 days, certification renewal is required and below is the command.

$ sudo certbot renew --dry-run


Nodejs에서 배치(Batch) 기능 사용하기(node-schedule)

예정된 시간에 작업을 수행하는 node-schedule

별도의 SQL문을 사용해 배치(Batch) 기능을 사용하던 것과 비교하면 정말 편하게 프로그래밍이 가능하도록 도와주는 라이브러리입니다.

배치 기능을 사용할 수 있는 대표 라이브러리는 크게 3가지(Agenda, node-cron, node-schedule)이며, 인기는 다음과 같습니다.

  1. Agenda (2021/12/22 기준 주간 다운로드 수 56,319)
  2. node-cron(2021/12/22 기준 주간 다운로드 수 219,168)
  3. node-schedule(2021/12/22 기준 주간 다운로드 수 507,675)

필요한 기능이 동일하다면 사용자가 많은 쪽이 관련 정보도 얻기 쉬우므로 node-schedule을 사용해보겠습니다.

npm install node-schedule

설치 후 해당 라이브러리를 import합니다.

import schedule from 'node-schedule';

그리고 서버를 가동하면 바로 실행될 수 있도록 index.js에 실행 함수를 넣어주면 됩니다.

실행될 조건(시간 또는 반복 주기)을 넣어주면 해당 조건에 맞춰 함수를 실행합니다.

const regularExec = schedule.scheduleJob('0 0 12 * * *', ()=>{ // 매일 낮 12시 정각마다 실행



위 함수는 매일 낮 12시마다 실행됩니다.

scheduleJob의 첫 번째 파라미터의 값은 다음과 같습니다.

*는 all과 값은 의미이며, 각 파라미터의 사이에는 빈칸을 넣어줍니다.

초를 넣는 부분인 second 에 *를 넣으면 모든 초마다 실행하라는 의미가 됩니다.

따라서 minute에 5, second에 *을 넣으면 5분00초부터 5분59초까지 함수가 총 60번 실행됩니다.

주기를 설정하는 방법도 있는데요.

second에 */5로 표기하면 초 단위를 5초 단위로 쪼갭니다.

따라서 5초에 한 번씩 실행하라는 의미가 됩니다.

취소는 cancel 메소드를 사용하면 됩니다.


유의할 점은 서버가 실행 중일 때만 해당 스케쥴러가 작동하며, 멀티프로세스를 가동하는 경우 중복으로 실행되지 않도록 별도의 설정을 해주어야 합니다.

그럼 서버가 열심히 일하도록 스케쥴러 기능을 요긴하게 사용해 주세요!