js package JS time formatting function

Convert current timestamp to date format (year-month-day-hour-minute-second)

function formatDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  const hours = ('0' + date.getHours()).slice(-2);
  const minutes = ('0' + date.getMinutes()).slice(-2);
  const seconds = ('0' + date.getSeconds()).slice(-2);
  return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
}

Instructions:

const formattedDate = formatDate(); // '2022-01-01-13-00-00'(示例)
console.log(formattedDate);

Display the month/day of the week before the current date on the X-axis of ECharts

// 在 ECharts 的 X 轴上显示当前日期前一周的月日
        const today = new Date() // 当前日期
        const lastWeek = new Date(
          today.getFullYear(),
          today.getMonth(),
          today.getDate() - 6
        ) // 最近一周的日期
        const xAxisData = [] // 存储要显示的日期字符串
        for (let i = lastWeek.getTime(); i <= today.getTime(); i += 86400000) {
          const date = new Date(i)
          xAxisData.push(
            date.toLocaleDateString('en-US', {
              month: 'numeric',
              day: 'numeric',
            })
          )
        }

Instructions:

  xAxis: {
    type: 'category',
    data: xAxisData,
    axisLabel: {
      formatter: '{value}'
    }
  },

 Get the current time in vue and display it dynamically on the page

 In this Vue component, we use Createdlifecycle hooks to start timing update time when the component is created. setIntervalUse updateTimethe method called at every second interval to update the current time. In updateTimethe method , we use a method similar to native JavaScript to get the current time and set currentTimethe data in the Vue instance.

Finally, use double brackets to bind currentTimedata to display the current time.

<template>
  <div>{
   
   { currentTime }}</div>
</template>

<script>
  export default {
    data() {
      return {
        currentTime: ''
      };
    },
    created() {
      this.updateTime();
      setInterval(() => {
        this.updateTime();
      }, 1000);
    },
    methods: {
      updateTime() {
        const now = new Date();
        const year = now.getFullYear();
        const month = ('0' + (now.getMonth() + 1)).slice(-2); // 月份从 0 开始
        const date = ('0' + now.getDate()).slice(-2);
        const hours = ('0' + now.getHours()).slice(-2);
        const minutes = ('0' + now.getMinutes()).slice(-2);
        const seconds = ('0' + now.getSeconds()).slice(-2);

        this.currentTime = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
      }
    }
  };
</script>

Guess you like

Origin blog.csdn.net/m0_61663332/article/details/130942359