[JS] 자바스크립트의 Intl API
2022. 10. 12. 09:18ㆍJavascript/개념
1. Intl API 소개
여러가지 언어로 서비스를 할 수 있도록 웹 애플리케이션을 설계하고 구현하는 과정을 국제화(internalization)
자바스크립트에서는 이러한 데이터 포멧팅 문제를 해결해주기 위해서 Intl API를 제공하고 있다.
2. Intl.DateTimeFormat
Intl API의 Intl.DateTimeFormat를 사용하면 날짜나 시간 데이터를 쉽게 국제화를 할 수 있다.
포멧팅 옵션으로 dateStyle과 timeStyle이 자주 사용되는데 full, long, medium, short 중 하나로 설정할 수 있다.
> new Intl.DateTimeFormat("ko", { dateStyle: 'full' }).format(new Date())
'2022년 3월 8일 화요일'
> new Intl.DateTimeFormat("ko", { dateStyle: 'long' }).format(new Date())
'2022년 3월 8일'
> new Intl.DateTimeFormat("ko", { dateStyle: 'medium' }).format(new Date())
'2022. 3. 8.'
> new Intl.DateTimeFormat("ko", { dateStyle: 'short' }).format(new Date())
'22. 3. 8.'
> new Intl.DateTimeFormat("ko", { timeStyle: 'full' }).format(new Date())
'오후 10시 58분 25초 미 동부 표준시'
> new Intl.DateTimeFormat("ko", { timeStyle: 'long' }).format(new Date())
'오후 10시 58분 31초 GMT-5'
> new Intl.DateTimeFormat("ko", { timeStyle: 'medium' }).format(new Date())
'오후 10:58:37'
> new Intl.DateTimeFormat("ko", { timeStyle: 'short' }).format(new Date())
'오후 10:58'
3. Intl.NumberFormat
통화(currency), 백분율, 무게, 길이, 속도, 온도와 같이 단위가 있는 숫자 데이터를 다룰 때 사용
- 백분률 데이터를 다룰 때는 style 옵션을 percent로 설정하고, format() 함수에 소수를 넘김
> new Intl.NumberFormat('ko', { style: 'percent' }).format(0.7)
'70%'
> new Intl.NumberFormat('ko', { style: 'percent' }).format(1 / 4)
'25%'
- 통화 데이터를 다룰 때는 style 옵션을 currency로 주고, currency 옵션에 통화 코드를 넘김
> new Intl.NumberFormat('ko', { style: 'currency', currency: 'KRW' }).format(50000)
'₩50,000'
> new Intl.NumberFormat('ko', { style: 'currency', currency: 'USD' }).format(40.56)
'US$40.56'
- 그 밖에 다른 단위를 사용할 때는 style 옵션을 unit으로 주고, unit 옵션에 단위 코드를 넘김
> new Intl.NumberFormat('ko', { style: 'unit', unit: 'kilogram' }).format(50)
'50kg'
> new Intl.NumberFormat('ko', { style: 'unit', unit: 'pound' }).format(110)
'110lb'
참고
'Javascript > 개념' 카테고리의 다른 글
[JS] if-else if | if - if 차이점 (0) | 2022.02.28 |
---|---|
[JS] JSON.parse / JSON.stringify (0) | 2022.02.18 |
[JS] new Set 객체 (0) | 2022.02.14 |
[JS] 조건문 if switch (0) | 2022.01.25 |
[JS] 전개 연산자 Spread Operator (0) | 2022.01.25 |