자바스크립트에서 날짜 시간 다루는 법>>>
======================================
원래있는 방법>
let date = new Date(2022,9 , 31)
function addMonths(date, months){
let d = date.getDate();
date.setMonth(date.getMonth() +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
console.log(addMonths(date, 1));
자바스크립트 중 인터네셔널 기능
Intl 기능 써도됨 (날짜 포맷팅이 쉽다.)
let date = new Date();
let a = new Intl.DateTimeFormat('kr').format(date); // 저기 kr되있는곳에 en 뭐 fr 다국어 다넣으면다됨
console.log(a); // 이러면 한국시간으로 짜잔 나옴
//타임 스타일도 됨
let a = new Intl.DateTimeFormat('kr' , {
dateStyle : 'full', timeStyle : "full"
}).format(date); // 저기 kr되있는곳에 en 뭐 fr 다국어 다넣으면다됨
console.log(a); // 이러면 한국시간으로 짜잔 나옴
*Intl쓰면 시간차 쉽게 표현 가능함.
let date = new Date();
let a = new Intl.RelativeTimeDormat().format(-10, 'days')
console.log(a); // 몇일전
let a = new Intl.RelativeTimeDormat().format(-10, 'hours')
console.log(a); // 몇시간전
let a = new Intl.RelativeTimeDormat().format(-10, 'months')
console.log(a); // 몇개월 전
이게 싫으면,,,
앞으로
js 신 기능인데,
Temporal 이라는 기능임.
현재시간 구하기
import {Temporal} form '@js-temporal/polyfill'; //폴리필가져오기
let now = Temporal.Now.plainDateTimeISO();
console.log(now.toString());
let now = Temporal.Now.plainDateISO();
console.log(now.toString());
let now = Temporal.Now.plainTimeISO();
console.log(now.toString());
Temporal로 시간 생성하기
let now = Temporal.PlainDate(2022, 9, 9);
console.log(now.toString());
Temporal 로 시간 덧셈 뺼셈 가능
let now = Temporal.Now.plainDateTimeISO(); //현재날짜를 구하고
now = now.add({ // 현재날자에다가 10일을 더하고싶다면 이렇게..
days : 10
})
console.log(now.toString());
let now = Temporal.Now.plainDateTimeISO(); //현재날짜를 구하고
now = now.add({ // 현재날자에다가 10일을 더하고 , 년 월 일까지 더하기
days : 10, months : 3
})
console.log(now.toString());
let now = Temporal.Now.plainDateTimeISO(); //현재날짜를 구하고
now = now.subtract({ // 현재날자에다가 10일을 빼기 , 년 월 일까지 빼기
days : 10, months : 3
})
console.log(now.toString());
let now = Temporal.Now.plainDateTimeISO(); //현재날짜를 구하고
now = now.round({ // 시간 반올림 하고싶으면..
smallestUnit: 'hour', roundingMode: 'floor'
});
console.log(now.toString());
Dday 계산도 됨.
let Dday = Temporal.PlainDateTime.from('2022-09-30T12:00:00');
let now = Temporal.Now.plainDateTimeISO(); //현재날짜를 구하고
const result = Dday.since(today);
console.log(result.toString());
console.log(result.days);
console.log(result.hours);