uniapp时间戳转换

全局

 在 main.js 文件里面声明以下内容,注意如何是秒需要在Date中 * 1000,如果是毫秒的话不需要 * 1000

Vue.filter("formatTime",function(timestamp) {
	const date = new Date(timestamp * 1000)
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hours = date.getHours()
	const minutes = date.getMinutes()
	const seconds = date.getSeconds()
	const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
	return formattedTime
})

 局部

那个页面需要用到在那个页面写以下内容

filters: {
    formatTime(timestamp){
	    const date = new Date(timestamp * 1000)
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		const hours = date.getHours()
		const minutes = date.getMinutes()
		const seconds = date.getSeconds()
		const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		return formattedTime
	}
},

 在页面中使用

<template>
    <view>
        {{dateTime | formatTime}}
    </view>
</template>

<script>
    export default {
        data(){
            return {
                dateTime: 1694572566,
            }
        }
    }
</script>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
答案: 可以在uniapp中使用filters来实现将时间戳转换成具体时间的功能,具体步骤如下: 1. 在uniapp项目中的filters文件夹中创建一个js文件,命名为timestamp.js,用于编写时间戳转换的逻辑。 2. 在timestamp.js中,定义一个名为formatTimestamp的过滤器函数,代码如下: ```javascript // timestamp.js export function formatTimestamp(timestamp) { const date = new Date(timestamp * 1000) const year = date.getFullYear() const month = (date.getMonth() + 1).toString().padStart(2, '0') const day = date.getDate().toString().padStart(2, '0') const hour = date.getHours().toString().padStart(2, '0') const minute = date.getMinutes().toString().padStart(2, '0') const second = date.getSeconds().toString().padStart(2, '0') return `${year}-${month}-${day} ${hour}:${minute}:${second}` } ``` 这个函数的参数是一个时间戳,单位是秒,函数的作用是将这个时间戳转换成具体时间。具体实现过程是,先将时间戳乘以1000,然后使用Date对象创建一个表示当前时间的对象,然后将年、月、日、时、分、秒分别提取出来,最后将这些信息格式化成一个字符串返回即可。 3. 在需要使用过滤器的页面或组件中,使用import语句引入timestamp.js文件。 4. 在页面或组件的template中,使用filters属性来注册formatTimestamp过滤器,在需要显示时间的地方使用{{timestamp | formatTimestamp}}语法即可。 示例代码如下: ```html <!-- index.vue --> <template> <view>{{ timestamp | formatTimestamp }}</view> </template> <script> import { formatTimestamp } from '@/filters/timestamp' export default { filters: { formatTimestamp, }, data() { return { timestamp: 1680609823, } }, } </script> ``` 注意:以上代码中需要将timestamp.js文件放在filters文件夹中,并且需要在index.vue文件中使用import语句引入timestamp.js文件。同时,在页面或组件的filters属性中注册过滤器时,需要将过滤器函数名和函数名对应的变量名都写在一个对象中,以确保过滤器可以正常工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深夜里的思念

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值