import React from "react";
import styles from "../styles/date_time_display.less";

class DateTimeDisplay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      now: new Date(),
    };
    this.timer = null;
  }

  componentDidMount() {
    // 每秒更新时间
    this.timer = setInterval(() => {
      this.setState({ now: new Date() });
    }, 1000);
  }

  componentWillUnmount() {
    // 清除定时器
    clearInterval(this.timer);
  }

  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date
      .getDate()
      .toString()
      .padStart(2, "0");
    const weekdays = [
      "星期日",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六",
    ];
    const weekday = weekdays[date.getDay()];

    const hours = date
      .getHours()
      .toString()
      .padStart(2, "0");
    const minutes = date
      .getMinutes()
      .toString()
      .padStart(2, "0");
    const seconds = date
      .getSeconds()
      .toString()
      .padStart(2, "0");

    return (
      <>
        <span className={styles.date}>{`${year}/${month}/${day} `}</span>
        <span className={styles.week}>{`${weekday} `}</span>
        <span className={styles.time}>{`${hours}:${minutes}:${seconds}`}</span>
      </>
    );
  }

  render() {
    const { now } = this.state;
    return this.formatDate(now);
  }
}

export default DateTimeDisplay;
