Vue自定义时间日期格式将毫秒数转化为‘yyyy-MM-dd hh:mm:ss’

本文介绍如何在Vue项目中创建并应用全局过滤器,包括步骤说明与具体示例,帮助开发者快速掌握过滤器的配置及使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 新建 filter 文件夹,在filter新建index.js,创建全局过滤器

//filter/index.js内容

import Vue from 'vue'

Vue.filter('date', function (dateTime, fmt) {
    var dateTime = new Date(dateTime);
    var o = {
        "M+": dateTime.getMonth() + 1,               //月份   
        "d+": dateTime.getDate(),                    //日   
        "h+": dateTime.getHours(),                   //小时   
        "m+": dateTime.getMinutes(),                 //分   
        "s+": dateTime.getSeconds(),                 //秒   
        "q+": Math.floor((dateTime.getMonth() + 3) / 3), //季度   
        "S": dateTime.getMilliseconds()             //毫秒   
    };

    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (dateTime.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
})

 记得在main.js中: 

import './filter/index.js'

这样vue自定义的全局过滤器就注册完成了,如何使用呢?

1、直接在template中应用:

{{ 1536586255745 | date('yyyy-MM-dd hh:mm:ss')}}

2、在js中应用:

 

<think>我们使用Vue 3和Composition API(<script setup>)来实现这个需求。 目标:获取明天上午4:55的时间,并格式化为YYYY-MM-DD HH:mm:ss。 步骤: 1. 使用JavaScript的Date对象或dayjs库(如果项目已使用)来操作日期。 2. 获取当前时间,然后计算明天的时间(当前日期+1天)。 3. 设置时间为上午4:55。 4. 格式化为指定的字符串。 由于用户提供的引用[1]中使用了dayjs,我们可以参考使用dayjs(推荐,因为dayjs轻量且API友好)。 如果项目没有安装dayjs,需要先安装:npm install dayjs 但是,如果不想引入额外的库,也可以使用原生Date对象。 这里提供两种方案: 方案一:使用dayjs(推荐) 引用[1]中已经使用了dayjs,我们可以按照类似方式。 方案二:使用原生Date 考虑到用户可能没有安装dayjs,我们可以同时给出两种方案。 由于用户要求格式YYYY-MM-DD HH:mm:ss,dayjs可以直接通过.format('YYYY-MM-DD HH:mm:ss')实现。 而原生Date则需要手动拼接或者使用Intl.DateTimeFormat等,但手动拼接容易出错,所以建议使用toLocaleString等方法并指定区域选项,但这样不能完全保证格式一致(比如月份和日期可能需要补零)。 因此,更推荐使用dayjs,因为其简单可靠。 下面分别给出两种实现: 方案一(使用dayjs): 1. 导入dayjs。 2. 获取当前日期,然后加上1天得到明天。 3. 设置时间为4:55(注意:上午4:55,24小时制就是4:55,所以使用hour(4).minute(55))。 4. 格式化。 方案二(使用原生Date): 1. 创建一个新的Date对象,设置为当前时间。 2. 将日期增加1天(使用setDate(getDate()+1))。 3. 设置小时为4,分钟为55,秒为0(注意:毫秒也设置为0,避免影响)。 4. 然后使用函将其格式化为YYYY-MM-DD HH:mm:ss(需要处理补零)。 由于用户提供的代码示例中使用了dayjs,并且dayjs在格式化方面非常方便,所以优先展示dayjs方案。 代码实现(使用dayjs): 在Vue组件的<script setup>部分: 注意:由于是明天上午4:55,所以是固定的时间点,不需要每秒更新(除非你想显示当前时间到那个时间点的倒计时?)。但根据问题,我们只需要获取一次并显示。 但是,如果用户需要实时显示当前时间到明天4:55的倒计时,那就会复杂一些。不过问题只要求获取那个时间点并格式化。 因此,我们只计算一次。 示例代码: 使用dayjs: ```vue <script setup> import dayjs from 'dayjs'; // 计算明天上午4:55的时间 const getTomorrowTime = () => { // 获取当前时间,然后加1天,并设置小时和分钟 return dayjs().add(1, 'day').hour(4).minute(55).second(0).format('YYYY-MM-DD HH:mm:ss'); }; const tomorrowTime = getTomorrowTime(); </script> <template> <div>{{ tomorrowTime }}</div> </template> ``` 方案二:使用原生Date(不使用dayjs): 我们需要一个补零函,确保月份、日期、小时、分钟、秒都是两位。 ```vue <script setup> import { ref, onMounted } from 'vue'; // 补零函 const padZero = (num) => { return num.toString().padStart(2, '0'); }; // 使用原生Date获取明天4:55的时间并格式化 const getTomorrowTime = () => { const now = new Date(); const tomorrow = new Date(now); tomorrow.setDate(now.getDate() + 1); tomorrow.setHours(4, 55, 0, 0); // 设置小时、分钟、秒、毫秒 const year = tomorrow.getFullYear(); const month = padZero(tomorrow.getMonth() + 1); // 月份从0开始,所以+1 const day = padZero(tomorrow.getDate()); const hour = padZero(tomorrow.getHours()); const minute = padZero(tomorrow.getMinutes()); const second = padZero(tomorrow.getSeconds()); return `${year}-${month}-${day} ${hour}:${minute}:${second}`; }; const tomorrowTime = ref(''); onMounted(() => { tomorrowTime.value = getTomorrowTime(); }); </script> <template> <div>{{ tomorrowTime }}</div> </template> ``` 注意:在onMounted中设置是为了确保在客户端执行(如果是在服务端渲染,Date对象可能因为时区问题产生差异)。但如果是纯客户端,也可以在setup顶部直接调用。 但是,由于我们使用了ref,并且onMounted是在客户端执行的,所以可以避免SSR中的问题。 然而,根据问题,我们只需要获取一次,所以两种方式都可以。 推荐使用dayjs,因为日期操作更简单,时区处理也更方便(虽然这里没有时区换,但dayjs默认本地时间,与Date一致)。 关于时区:以上两种方法都是基于用户本地时间。如果希望使用UTC时间,dayjs有utc插件,而Date可以使用getUTC系列方法。 但问题没有特别说明,我们按本地时间处理。 总结:推荐使用dayjs方案,代码简洁清晰。 相关问题: 1. 在Vue中如何实时显示当前时间并每秒更新? 2. 如何使用dayjs处理时区换? 3. 在JavaScript中如何计算两个日期之间的时间差?</think>在 Vue 中获取明天上午 4:55 的时间并格式化为 `YYYY-MM-DD HH:mm:ss`,可以使用 JavaScript 的 `Date` 对象或 `dayjs` 库(更推荐)。以下是两种实现方案: ### 方案一:使用原生 JavaScript Date 对象(无需额外库) ```vue <script setup> import { ref, onMounted } from 'vue' const tomorrowTime = ref('') function getTomorrowTime() { // 1. 获取当前时间 const now = new Date() // 2. 创建明天的日期对象 const tomorrow = new Date(now) tomorrow.setDate(now.getDate() + 1) // 加1天 // 3. 设置时间为上午4:55 tomorrow.setHours(4, 55, 0, 0) // 小时,分钟,秒,毫秒 // 4. 格式化为 YYYY-MM-DD HH:mm:ss const year = tomorrow.getFullYear() const month = String(tomorrow.getMonth() + 1).padStart(2, '0') // 月份补零 const day = String(tomorrow.getDate()).padStart(2, '0') // 日期补零 const hours = String(tomorrow.getHours()).padStart(2, '0') // 小时补零 const minutes = String(tomorrow.getMinutes()).padStart(2, '0') // 分钟补零 const seconds = String(tomorrow.getSeconds()).padStart(2, '0') // 秒补零 return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` } onMounted(() => { tomorrowTime.value = getTomorrowTime() }) </script> <template> <div>明天上午4:55: {{ tomorrowTime }}</div> </template> ``` ### 方案二:使用 dayjs 库(更简洁,推荐) 1. 先安装 dayjs: ```bash npm install dayjs ``` 2. Vue 组件实现: ```vue <script setup> import { ref, onMounted } from 'vue' import dayjs from 'dayjs' const tomorrowTime = ref('') function getTomorrowTime() { // 获取当前时间 → 加1天 → 设置时分秒 → 格式化 return dayjs() .add(1, 'day') // 加1天 .set('hour', 4) // 设置小时 .set('minute', 55) // 设置分钟 .set('second', 0) // 设置秒 .format('YYYY-MM-DD HH:mm:ss') // 格式化输出 } onMounted(() => { tomorrowTime.value = getTomorrowTime() }) </script> <template> <div>明天上午4:55: {{ tomorrowTime }}</div> </template> ``` ### 关键点说明: 1. **日期计算**: - `add(1, 'day')`:将当前日期增加1天 - `setDate(now.getDate() + 1)`:原生JS的日期增加方法 2. **时间设置**: - 使用 `.set('hour', 4).set('minute', 55)`(dayjs) - 或 `setHours(4, 55, 0, 0)`(原生Date) 3. **格式化**: - dayjs 直接使用 `.format('YYYY-MM-DD HH:mm:ss')` - 原生JS需要手动补零(`padStart(2, '0')`) ### 时区注意事项: 两种方法都使用**用户本地时区**。如果需要 UTC 时间: ```javascript // dayjs UTC 版本 dayjs.utc() .add(1, 'day') .hour(4).minute(55) .format('YYYY-MM-DD HH:mm:ss') // 原生 Date UTC 版本 new Date(Date.now() + 86400000) .toISOString() .replace('T', ' ') .substring(0, 19) ``` > 推荐使用 dayjs 方案,代码更简洁且避免手动处理日期边界问题(如月末/闰年)。[^1] ### 相关问题 1. 如何在 Vue 中实现实时更新的时钟? 2. dayjs 和 moment.js 的主要区别是什么? 3. 如何计算两个日期之间的时间差? 4. 在 JavaScript 中如何处理时区换? 5. Vue 组件中如何优雅地管理定时器?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值