(vue) vue project get date time week

(vue) vue project get date time week


Effect:
insert image description here

code:

<div class="top-time">
  <div class="time-currentDate">
    {
    
    {
    
     currentDate }}
    <div class="time-img">
      <img src="@/assets/image/icon-time.png" alt />
    </div>
  </div>
  <div class="time-Weekday">
    <span>{
    
    {
    
     currentWeekday }}</span>
    <span>{
    
    {
    
     currentTime }}</span>
  </div>
</div>

js

data() {
    
    
  return {
    
    
    currentDate: "",
    currentTime: "",
    currentWeekday: "",
  }  
},

created() {
    
    
  setInterval(() => {
    
     
    this.getCurrentDateTime();
    this.getCurrentWeekday();
  }, 1000);
},   

methods: {
    
    
  getCurrentDateTime() {
    
    
    const now = new Date();
    this.currentDate = now.toLocaleDateString();
    // this.currentTime = now.toLocaleTimeString(); // 时分秒格式
    this.currentTime = now.toLocaleTimeString([], {
    
    
      hour: "2-digit",
      minute: "2-digit",
    }); //时分格式
  },
  getCurrentWeekday() {
    
    
    const weekdays = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    const now = new Date();
    this.currentWeekday = weekdays[now.getDay()];
  },  
}

In the above code,
1. Call the getCurrentDateTime and getCurrentWeekday methods when the component is created through the created hook function, and save the obtained date, time and week in the data attribute. 2. Then, display the data
in the template through the interpolation expression { {}}.

The getCurrentDateTime method uses the toLocaleDateString and toLocaleTimeString methods to obtain localized date and time strings.
The getCurrentWeekday method uses the getDay method to obtain the index of the week corresponding to the current date, and then obtains the corresponding week text through the index.

  • time format

In the above code,
1. Set the second parameter of the toLocaleTimeString method to an empty array [],
2. Then pass an option object in the empty array { hour: '2-digit', minute: '2 -digit'}.
This options object specifies the display format for hours and minutes, '2-digit' means display numbers as two digits. With such a setting, the seconds will not be included in the generated time string.

Guess you like

Origin blog.csdn.net/qq_44754635/article/details/131891625