时间格式化工具

238 阅读3分钟

实现效果

1.gif

安装

npm install yg-moment

引入

import { dateFormat, getWeek, beforeDateFormat } from "yg-moment";

使用示例

<template>
  <div id="data-view">
    <h1>{{ time }}</h1>
    <h1>{{ week }}</h1>
    <h1>{{ beforeTime }}</h1>
  </div>
</template>

<script>
import { dateFormat, getWeek, beforeDateFormat } from "yg-moment";
export default {
  name: "YgMoment",
  data() {
    return {
      time: "",
      week: "",
      beforeTime: "",
    };
  },
  created() {
    this.init();
    setInterval(() => {
      this.init();
    }, 500);
  },
  methods: {
    /**
     * getWeek此函数用于获取当前日期或指定日期是星期几,并以中文形式返回。
     * 如果未提供时间戳,则使用当前周几。
     * 返回值为0-6,分别代表星期日到星期六。
     * @param {string} [timestamp] - 可选参数,表示要查询的时间戳。如果未提供,则使用当前时间。
     * @returns {string} 中文表示的星期几,例如"星期一"。
     */
    getWeek() {
      this.week = getWeek();
    },

    /**
     * beforeDateFormat此函数用于获取指定日期离当前时间间隔多久,并以中文形式返回。(1年前,1个月前,1周前,1天前,1小时前,1分钟前,刚刚。)
     * 如果未提供时间戳,返回undefined 页面不报错也不做任何显示。
     * 返回值为0-6,分别代表星期日到星期六。
     * @param {string} [timestamp] - 必传参数,表示要查询的时间戳 必须是当前时间之前的时间戳,否则会返回 刚刚。
     * @returns {string}返回【 1年前,1个月前,1周前,1天前,1小时前,1分钟前,刚刚】
     */
    beforeDateFormat() {
      // this.beforeTime = beforeDateFormat(new Date('2024-07-04 18:30:00').getTime());
      this.beforeTime = beforeDateFormat(new Date("2024-07-04").getTime());
    },

    /**
     * getTime此函数用于获取时间  格式默认返回:YYYY-mm-dd HH:MM:SS   年-月-日 时:分:秒
     * 如果未提供时间戳,返回当前时间。
     * @param {string} [format="YYYY-mm-dd HH:MM:SS"] - 必传参数,表示要格式化的时间格式
     * @param {string} [timestamp] - 可选参数,表示要查询的时间戳,不传则默认为当前时间戳
     * @returns {string}返回  年-月-日 时:分:秒
     */
    getTime() {
      //    this.time = dateFormat("YYYY-mm-dd");// 返回 2024-07-04
      this.time = dateFormat("YYYY-mm-dd HH:MM:SS"); // 返回 2024-07-04 18:30:00
    },
	
    init() {
      this.getTime();
      this.getWeek();
      this.beforeDateFormat();
    },
  },
};
</script>

<style scoped>
</style>

文章部分 到此结束,下面是使用帮助。可以不看。日期定制化需求比较多时可查看使用帮助

使用帮助

yg-moment格式化时间说明文档
格式代码说明返回值例子
M数字表示的月份,没有前导零1到12
MM数字表示的月份,有前导零01到12
MMM三个字母缩写表示的月份Jan到Dec
MMMM月份,完整的文本格式January到December
Q季度1到4
D月份中的第几天,没有前导零1到31
DD月份中的第几天,有前导零01到31
d星期中的第几天,数字表示0到6,0表示周日,6表示周六
ddd三个字母表示星期中的第几天Sun到Sat
dddd星期几,完整的星期文本从Sunday到Saturday
w年份中的第几周如42:表示第42周
YYYY四位数字完整表示的年份如:2014 或 2000
YY两位数字表示的年份如:14 或 98
A大写的AM PMAM PM
a小写的am pmam pm
HH小时,24小时制,有前导零00到23
H小时,24小时制,无前导零0到23
hh小时,12小时制,有前导零00到12
h小时,12小时制,无前导零0到12
m没有前导零的分钟数0到59
mm有前导零的分钟数00到59
s没有前导零的秒数1到59
ss有前导零的描述01到59
XUnix时间戳1411572969

博客 | NPM地址 | git源码 | gitee源码