Vue中获取当前时间,可用于判断信息是否已过有效时间

本文介绍了一个基于Vue的表格组件实现,该组件能够实时显示数据的状态,如数据是否已失效,通过比较当前时间和数据的截止时间来动态更新状态显示。文章详细展示了如何使用Element UI的表格组件和自定义slot来实现这一功能。

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

<template>
    <div class="content-wrapper">
        <section>
            <el-table border stripe :data="datas"  highlight-current-row
                      @current-change="handleCurrentChange"
                      width="100%" tooltip-effect="light" v-loading="requested">

                <el-table-column label="截止时间" :show-overflow-tooltip="true" prop="endTime"
                                 header-align="center" align="center">
                </el-table-column>
                
                <el-table-column label="状态" header-align="center" align="center">
                    <template slot-scope="scope">
                        <el-tag type="info" v-if="currentTime > scope.row.endTime">失效</el-tag>
                        <el-tag type="success" v-if="currentTime < scope.row.endTime">未失效</el-tag>
                    </template>
                </el-table-column>
                
            </el-table>
        </section>
    </div>
</template>
<style>

</style>
<script>
    export default {
        data() {
            return {
                queryForm: {
                    title: '',
                    page: 1,
                    size: 10
                },
                datas: [],
                requested: false,
                currentTime: '',
            }
        },
        mounted() {
            this.query(this.queryForm.page, this.queryForm.size);
        },
        methods: {
            query() {
                this.requested = true;
                this.http.get('/admin/messageInfo', this.queryForm).then(resp => {
                    this.currentTime = this.format(new Date(), "yyyy-MM-dd HH:mm:ss");
                    this.currentRow = null;
                    this.datas = resp.data.content;
                }).finally(() => {
                    this.requested = false;
                });
            },
            format(date, fmt) {
                let o = {
                    "M+": date.getMonth() + 1, //月份
                    "d+": date.getDate(), //日
                    "H+": date.getHours(), //小时
                    "m+": date.getMinutes(), //分
                    "s+": date.getSeconds(), //秒
                    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                    "S": date.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (let 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;
            },
        }
    }
</script>

需要注意的一点是:HH才是24小时制,hh是12小时制

因此如果用value-format时间组件,组件只会保留日期的选择,会失去时间的选择

<think>我们正在解决如何获取当前时间的年月并比较的问题。在Vue中,我们可以使用JavaScript的Date对象来获取当前的年份和月份,然后进行比较。以下步骤将指导你完成: 1. **获取当前年份和月份**: - 使用`new Date()`创建当前时间的Date对象。 - 使用`getFullYear()`获取当前年份(四位数)。 - 使用`getMonth()`获取当前月份(注意:月份从0开始,0代表一月,11代表十二月,所以需要加1)。 2. **比较年月**: - 我们可以将年份和月份组合成一个数字(如:年份*100 + 月份)以便比较。这样,2023年5月将变成202305,2023年4月将变成202304,这样可以直接比较数字大小。 - 或者,也可以分别比较年份和月份。 3. **在Vue中的使用**: - 可以在data中定义变量存储当前年月。 - 在方法中定义比较函数。 - 在生命周期钩子(如mounted)中初始化当前年月。 下面是一个完整的Vue组件示例,展示如何获取当前年月,并比较两个年月(这里比较当前年月和一个固定年月): ```vue <template> <div> <p>当前年月:{{ currentYearMonth }}</p> <p>固定年月:{{ fixedYearMonth }}</p> <p>比较结果:{{ comparisonResult }}</p> </div> </template> <script> export default { data() { return { currentYear: 0, currentMonth: 0, fixedYear: 2023, // 固定年份 fixedMonth: 5 // 固定月份(5月) }; }, computed: { // 计算属性:当前年月(字符串形式,如2023-05) currentYearMonth() { return `${this.currentYear}-${this.currentMonth.toString().padStart(2, '0')}`; }, // 固定年月(字符串形式) fixedYearMonth() { return `${this.fixedYear}-${this.fixedMonth.toString().padStart(2, '0')}`; }, // 比较当前年月和固定年月 comparisonResult() { // 将年月转换为数字(年份*100 + 月份)以便比较 const current = this.currentYear * 100 + this.currentMonth; const fixed = this.fixedYear * 100 + this.fixedMonth; if (current > fixed) { return '当前年月晚于固定年月'; } else if (current < fixed) { return '当前年月早于固定年月'; } else { return '当前年月等于固定年月'; } } }, mounted() { // 在组件挂载时获取当前年月 this.getCurrentYearMonth(); }, methods: { getCurrentYearMonth() { const now = new Date(); this.currentYear = now.getFullYear(); this.currentMonth = now.getMonth() + 1; // 月份从0开始,需要+1 } } }; </script> ``` ### 说明: 1. **获取当前年月**:在`mounted`生命周期钩子中调用`getCurrentYearMonth`方法,该方法使用`Date`对象获取当前年份和月份,并更新到data中。 2. **计算属性**:使用计算属性`currentYearMonth`和`fixedYearMonth`将年月格式化为字符串(如2023-05)。`padStart`用于确保月份总是两位数(如5变成05)。 3. **比较逻辑**:在计算属性`comparisonResult`中,我们将年月转换成数字(例如2023年5月变成202305)进行比较。这样可以直接使用数字的大小来判断年月的先后。 ### 其他比较方式: 如果你想比较两个任意的年月,可以封装一个方法: ```javascript methods: { compareYearMonth(year1, month1, year2, month2) { const num1 = year1 * 100 + month1; const num2 = year2 * 100 + month2; if (num1 > num2) return 1; // 第一个年月晚于第二个 else if (num1 < num2) return -1; // 第一个年月早于第二个 else return 0; // 相等 } } ``` 然后在需要的地方调用这个方法。 ### 注意事项: - 月份获取时注意加1,因为JavaScript中月份是从0开始的。 - 比较时使用数字比较可以避免复杂的条件判断(先比较年份,年份相同再比较月份)。 ### 相关问题: 1. 如何在Vue中格式化日期? 2. Vue中如何实现日期的国际化显示? 3. 如何在Vue中使用第三方日期库(如Moment.js或date-fns)? 以上方法都是基于原生JavaScript的Date对象,如果你需要更复杂的日期操作,可以考虑使用第三方库,如date-fns或day.js,它们体积小且功能强大。</think>在 Vue获取当前年月并进行比较,可以通过 JavaScript 的 Date 对象实现。以下是完整解决方案: ### 获取当前年月并比较的完整实现 ```vue <template> <div> <p>当前年月: {{ currentYearMonth }}</p> <p>比较结果: {{ comparisonResult }}</p> <button @click="compareWithTarget(2023, 5)">与2023年5月比较</button> <button @click="compareWithTarget(2025, 8)">与2025年8月比较</button> </div> </template> <script> export default { data() { return { currentYear: 0, currentMonth: 0, comparisonResult: "" }; }, computed: { // 计算当前年月字符串(格式:YYYY-MM) currentYearMonth() { return `${this.currentYear}-${this.currentMonth.toString().padStart(2, '0')}`; } }, mounted() { // 组件挂载时获取当前年月 this.getCurrentYearMonth(); }, methods: { // 获取当前年月 getCurrentYearMonth() { const now = new Date(); this.currentYear = now.getFullYear(); this.currentMonth = now.getMonth() + 1; // 月份从0开始,需要+1 }, // 比较当前年月与目标年月 compareWithTarget(targetYear, targetMonth) { // 计算当前年月数值(年份*100 + 月份) const current = this.currentYear * 100 + this.currentMonth; const target = targetYear * 100 + targetMonth; if (current > target) { this.comparisonResult = `当前年月 ${this.currentYearMonth} 晚于 ${targetYear}-${targetMonth}`; } else if (current < target) { this.comparisonResult = `当前年月 ${this.currentYearMonth} 早于 ${targetYear}-${targetMonth}`; } else { this.comparisonResult = `当前年月 ${this.currentYearMonth} 等于 ${targetYear}-${targetMonth}`; } } } }; </script> ``` ### 关键说明 1. **获取当前年月** ```javascript const now = new Date(); const year = now.getFullYear(); // 获取当前年份(四位数) const month = now.getMonth() + 1; // 月份从0开始,需要+1 ``` 2. **年月比较逻辑** - 将年月转换为数字格式:`年份 * 100 + 月份` - 示例:2023年5月 → `2023 * 100 + 5 = 202305` - 通过比较数值大小判断时间先后 ```javascript const current = this.currentYear * 100 + this.currentMonth; const target = targetYear * 100 + targetMonth; if (current > target) { // 当前年月晚于目标年月 } else if (current < target) { // 当前年月早于目标年月 } else { // 年月相同 } ``` 3. **格式化显示** ```javascript // 月份补零显示(5 → 05) const formattedMonth = month.toString().padStart(2, '0'); // 完整年月格式:YYYY-MM const yearMonth = `${year}-${formattedMonth}`; ``` ### 应用场景示例 1. **截止日期检查** ```javascript checkDeadline() { const current = new Date().getFullYear() * 100 + (new Date().getMonth() + 1); const deadline = 2023 * 100 + 12; // 2023年12月 if (current > deadline) { alert("已超过截止日期!"); } } ``` 2. **订阅有效期验证** ```javascript validateSubscription(endYear, endMonth) { const current = this.currentYear * 100 + this.currentMonth; const end = endYear * 100 + endMonth; return current <= end; } ``` ### 注意事项 1. **时区问题**:如果需要精确到用户本地时间,可以使用: ```javascript const now = new Date(); const year = now.getUTCFullYear(); const month = now.getUTCMonth() + 1; ``` 2. **性能优化**:频繁获取时间时可缓存结果 ```javascript setInterval(() => { this.getCurrentYearMonth(); }, 60000); // 每分钟更新一次 ``` 3. **日期库推荐**:复杂日期操作建议使用第三方库 ```bash npm install dayjs ``` ```javascript import dayjs from 'dayjs'; const current = dayjs().format('YYYY-MM'); ``` ### 相关问题 1. 如何在Vue中实现日期选择器并比较日期范围? 2. 如何处理Vue中的时区转换问题? 3. Vue中如何实现倒计时功能? 4. 如何用Vue实现日历组件并高亮当前日期? 5. Vue中如何格式化不同语言的日期显示?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值