const addZero = (num: number): string => {
return num < 10 ? '0' + num : '' + num;
};
const getHourInfo = (hh: number): HourObj => {
if (hh > 12) {
return {
hour: addZero(hh - 12),
time: 'PM',
};
}
return {
hour: addZero(hh),
time: 'AM',
};
};
export const getCurrentDate = (): DateValues => {
const today = new Date();
const dayList = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
return {
hh: getHourInfo(today.getHours()),
mm: addZero(today.getMinutes()),
ss: addZero(today.getSeconds()),
YY: today.getFullYear(),
MM: today.getMonth() + 1,
DD: today.getDate(),
dd: dayList[today.getDay()].toUpperCase(),
};
};
내가 구현한 방법처럼 일일이 구하는 것보다 훨씬 편한 방법 같다
const options = {
weekday: 'short',
hour: 'numeric',
minute: 'numeric',
};
const time = new Intl.DateTimeFormat('en', options)
.format(new Date())
.toUpperCase();
timeArea.textContent = time;
반복 함수를 걸어주는 과정에서 콜백함수를 this.setState로 바로 넣어주니 this.render가 인식되지 않아 실행이 안됐다 → 더 알아봐야겠음
// (x)
mount() {
setInterval(
this.setState
, 1000);
}
// (o)
mount() {
setInterval(() => {
this.setState();
}, 1000);
}
class DigitalClock extends Component<undefined> {
state: DateValues;
constructor($target: Element) {
super($target);
this.state;
this.setState();
this.mount();
}
template() {
return `
<div class='digital-clock-container'>
<div class='digital-clock'>
<h1> ${this.state.dd}</h1>
<h1> ${this.state.hh.hour}</h1>
<h1> ${this.state.mm}</h1>
<h1> ${this.state.ss}</h1>
<h1> ${this.state.hh.time}</h1>
</div>
</div>
`;
}
render() {
this.$target.innerHTML = '';
this.$target.innerHTML = this.template();
}
setState() {
this.state = getCurrentDate();
this.render();
}
mount() {
setInterval(() => {
this.setState();
}, 1000);
console.log(this.state);
}
}
export default DigitalClock;