运行结果
代码
<template>
<view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
//时间转换为时间戳(十位时间戳即秒级时间戳)
const time = '2023-10-01 12:34:56'; // 时间格式为'年-月-日 时:分:秒'
const timestamp = Math.floor(new Date(time).getTime() / 1000); // 将时间转换成时间戳(以秒为单位)
console.log('时间戳为:'+timestamp);
//时间戳转换为时间'年-月-日 时:分:秒'
const dateObj = new Date(timestamp * 1000); // 将时间戳转换成日期对象
const year = dateObj.getFullYear(); // 获取年份
const month = (dateObj.getMonth() + 1).toString().padStart(2, '0'); // 获取月份,并补零
const day = dateObj.getDate().toString().padStart(2, '0'); // 获取日期,并补零
const hours = dateObj.getHours().toString().padStart(2, '0'); // 获取小时,并补零
const minutes = dateObj.getMinutes().toString().padStart(2, '0'); // 获取分钟,并补零
const seconds = dateObj.getSeconds().toString().padStart(2, '0'); // 获取秒数,并补零
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 拼接成指定格式的时间字符串
console.log('时间为:'+formattedDate);
}
}
</script>
<style>
</style>