js封装 JS 时间格式化函数

将当前时间戳转换为日期格式(年-月-日-时-分-秒)

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}`;
}

使用方法:

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

在 ECharts 的 X 轴上显示当前日期前一周的月/日

// 在 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',
            })
          )
        }

使用方法:

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

 在vue中获取当前时间动态显示在页面上

 在这个 Vue 组件中,我们使用了 Created 生命周期钩子来在组件创建时开始定时更新时间。使用 setInterval 在每秒钟的时间间隔内调用 updateTime 方法来更新当前时间。在 updateTime 方法中,我们使用类似原生 JavaScript 的方式来获取当前时间,并设置 Vue 实例中的 currentTime 数据。

最后,在模板中使用双括号绑定 currentTime 数据展示出当前时间。

<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>

猜你喜欢

转载自blog.csdn.net/m0_61663332/article/details/130942359