采用协调世界时(UTC+8)作为基准,避免跨时区问题

js具体实现:

// 创建一个表示当前时间的 Date 对象
const now = new Date();
// 获取当前时间的 UTC 时间戳,getTimezoneOffset() 返回的是本地时间与 UTC 时间的差值(分钟)
const utcTimestamp = now.getTime() + (now.getTimezoneOffset() * 60000);
// 加上 8 小时的毫秒数(8 * 60 * 60 * 1000)得到 UTC+8 的时间戳
const utc8Timestamp = utcTimestamp + (8 * 60 * 60 * 1000);
// 使用新的时间戳创建一个 Date 对象
const utc8Date = new Date(utc8Timestamp);

// 可以使用 toLocaleString 方法格式化输出
const formattedDate = utc8Date.toLocaleString('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false
});

console.log(formattedDate);

js封装成复用的函数

function getUTC8Date() {
  const now = new Date();
  const utcTimestamp = now.getTime() + (now.getTimezoneOffset() * 60000);
  const utc8Timestamp = utcTimestamp + (8 * 60 * 60 * 1000);
  return new Date(utc8Timestamp);
}

// 使用示例
const utc8Date = getUTC8Date();
const formattedDate = utc8Date.toLocaleString('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false
});

console.log(formattedDate);

vue组件中

<template>
  <div>
    <p>当前 UTC+8 时间: {{ utc8Time }}</p>
  </div>
</template>

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

export default {
  name: 'Test',
  setup() {
    const utc8Time = ref('');

    function getUTC8Date() {
      const now = new Date();
      const utcTimestamp = now.getTime() + (now.getTimezoneOffset() * 60000);
      const utc8Timestamp = utcTimestamp + (8 * 60 * 60 * 1000);
      return new Date(utc8Timestamp);
    }

    onMounted(() => {
      const utc8Date = getUTC8Date();
      utc8Time.value = utc8Date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    });

    return {
      utc8Time
    };
  }
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值