회사 프로젝트에서는 moment.js를 사용했는데, 오래된 패키지이기도 하고 날짜 변환이 잘 안되는 점이 있어서 개인 프로젝트에서는 day.js를 사용하고자 한다.
0. 패키지 설치
npm install dayjs
1. 전체코드
import dayjs from 'dayjs';
export const getCurrentAgeToNumber = (birth: string): number => {
// 현재 날짜 구하기
const currentDate = dayjs();
// 입력된 생년월일 문자열을 날짜 객체로 변환
const birthDate = dayjs(birth, { format: 'YYYYMMDD' });
// 현재 나이 계산
const age = currentDate.year() - birthDate.year();
// 생일이 지났는지 체크
if (
currentDate.month() < birthDate.month() ||
(currentDate.month() === birthDate.month() && currentDate.date() < birthDate.date())
) {
// 생일이 지나지 않았으면 나이에서 1을 빼줌
return age - 1;
}
return Number(age);
};
위처럼 dayjs() 를 호출한다.
2. 코드 설명
대략적으로 dayjs 패키지는 아래처럼 되어있다.
// Dayjs 이 클래스를 가져옴
declare function dayjs (date?: dayjs.ConfigType): dayjs.Dayjs
// 아래처럼 dayjs의 Dayjs 클래스를 부름
declare namespace dayjs {
interface ConfigTypeMap {
default: string | number | Date | Dayjs | null | undefined
}
export interface FormatObject { locale?: string, format?: string, utc?: boolean }
export type OptionType = FormatObject | string | string[]
class Dayjs {
year(): number
month(): number
date(): number
day(): number
hour(): number
minute(): number
second(): number
millisecond(): number
format(template?: string): string
...
const currentDate = dayjs();
dayjs()는 년, 월, 일, 시, 분, 초, 밀리세컨드의 형태대로 나오게 될것이다.
// dayjs의 가능한 formatting
export interface FormatObject { locale?: string, format?: string, utc?: boolean }
// 아래처럼 formatting
const birthDate = dayjs(birth, { format: 'YYYYMMDD' });
위처럼 yyyymmdd형태로 포메팅했다.
dayjs(birth)는 dayjs가 내부적으로 형식을 유추하여 파싱하는 것이며, 대부분의 표준 형식에 대해서는 자동으로 처리된다.
하지만 형식이 특별한 경우에는 제대로 동작하지 않을 수 있다.
반면에 dayjs(birth, { format: 'YYYYMMDD' })는 명시적으로 어떤 형식을 사용하여 birth를 해석하라고 지정하는 것이다.
이 경우에는 { format: 'YYYYMMDD' }에 지정된 형식에 따라 birth가 해석되며, { format: 'YYYYMMDD' } 대로 포메팅 못하면 dayjs(birth)처럼 행동하게 된다.
즉, 일반적이면
// 일반적으로
const birthDate = dayjs(birth);
// 내가 format을 확실히 정해주고 여기서 벗어나지 않는걸 원한다면
const birthDate = dayjs(birth, { format: 'YYYYMMDD' });
처럼 형식을 정해줄 수 있는것이다.
그래서 일반적이라면
const birthDate = dayjs(birth);
처럼 쓰는게 추천된다.
const birthDate = dayjs(birth).format('YYYYMMDD');
참고로 내가 직접 포메팅하고 싶으면 위처럼 작성하면 된다.
const currentDate = dayjs();
// 입력된 생년월일 문자열을 날짜 객체로 변환
const birthDate = dayjs(birth, { format: 'YYYYMMDD' });
const age = currentDate.year() - birthDate.year();
// 생일이 지났는지 체크하기 위해 월, 일끼리 비교
if (
currentDate.month() < birthDate.month() ||
(currentDate.month() === birthDate.month() && currentDate.date() < birthDate.date())
)
위처럼 년도, 월, 일만 뽑아서 계산할 수도 있다.
// number 정수형태로 타입제공
year(): number
const age = currentDate.year() - birthDate.year();
return Number(age);
정수형태로 타입 제공해서 Number로 타입변환까지 할 필요는 없지만, 확실히 하기 위해 추가했다.
'JaveScript > ExpressJS' 카테고리의 다른 글
ExpressJS와 ChatGPT 연동 (1) (2) | 2023.12.18 |
---|---|
닉네임 랜덤 제너레이터 (0) | 2023.12.17 |
ts-jenum으로 Enum객체 활용 (0) | 2023.12.13 |
expressjs + typeorm 0.3 세팅 후 사용법 (1) | 2023.12.12 |
morgan 세팅 (0) | 2023.11.30 |