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>