vue3使用组合式api将时间戳格式转换成时间格式(2023年09月28日 10:00)

场景1:直接转换成某一个值formattedDate
在Vue 3中,你可以使用组合式API中的计算属性来将13位时间戳转换成指定格式的日期。下面是一个示例代码:

<template>
  <div>
    <p>原始时间戳:{
   
   { timestamp }}</p>
    <p>转换后的日期:{
   
   { formattedDate }}</p>
  </div>
</template>

<script>
import { ref, computed } from 'vue';

export default {
  setup() {
    const timestamp = ref(1632800400000); // 13位时间戳,示例为2021年09月28日 10:00的时间戳

    const formattedDate = computed(() => {
      const date = new Date(timestamp.value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    });

    return {
      timestamp,
      formattedDate,
    };
  },
};
</script>

在上面的代码中,我们使用了ref来创建一个响应式的timestamp变量,它存储了13位时间戳。然后,我们使用computed来创建一个计算属性formattedDate,它会根据timestamp的值动态计算出格式化后的日期。在formattedDate的计算函数中,我们使用new Date(timestamp.value)来将时间戳转换成Date对象。然后,我们使用Date对象的方法来获取年、月、日、小时和分钟,并使用padStart方法来补齐位数。最后,我们将这些值拼接成指定格式的日期字符串,并返回给计算属性。
场景2:将后台返回的数组对象里面的所有时间戳准换成日期时间显示在界面上:

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        <p>原始时间戳:{
   
   { item.timestamp }}</p>
        <p>转换后的日期:{
   
   { formatDate(item.timestamp) }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const items = ref([
      { id: 1, timestamp: 1632800400000 },
      { id: 2, timestamp: 1632811200000 },
      { id: 3, timestamp: 1632822000000 },
    ]); // 示例数据,包含3个对象,每个对象都有一个13位时间戳字段

    const formatDate = (timestamp) => {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    };

    return {
      items,
      formatDate,
    };
  },
};
</script>

在上面的代码中,我们使用ref来创建一个响应式的items变量,它存储了一个包含3个对象的数组,每个对象都有一个13位时间戳字段。然后,我们定义了一个formatDate函数,它会将传入的13位时间戳格式化成指定的日期字符串。

在模板中,我们使用v-for指令来遍历items数组,并在每个对象的元素上展示原始时间戳和格式化后的日期。在展示格式化后的日期时,我们调用了formatDate函数,并将13位时间戳作为参数传入。

这样,当我们运行上面的代码时,就可以在界面上看到每个对象的原始时间戳和格式化后的日期了。

猜你喜欢

转载自blog.csdn.net/weixin_48138187/article/details/133699806