@jzh20060817/date-utils-esm
v1.0.0
Published
日期时间工具库 - ESM模块化
Downloads
138
Maintainers
Readme
日期时间工具库 - ESM模块化
一个基于ES6模块的日期时间工具库,提供多种日期时间处理功能,可在各种前端框架(Vue、Angular、React)中即装即用。
功能特性
- 日期格式化 (
formatDate) - 格式化日期为指定格式 - 相对时间 (
timeAgo) - 计算相对时间(如:刚刚、1分钟前、1小时前等) - 获取星期几 (
getWeekday) - 获取日期对应的星期几(数字或中文) - 日期加减 (
addDate) - 对日期进行加减操作 - 日期差计算 (
dateDiff) - 计算两个日期之间的天数差 - 判断闰年 (
isLeapYear) - 判断某一年是否为闰年 - 获取当月天数 (
getDaysInMonth) - 获取指定月份的天数 - 时间戳转换 (
timestampToDate) - 将时间戳转换为日期对象 - 日期比较 (
isSameDay) - 判断两个日期是否为同一天 - 获取季度 (
getQuarter) - 获取日期所在的季度(1-4) - 获取月份起止 (
getMonthStartEnd) - 获取指定月份的开始和结束日期 - 周末判断 (
isWeekend) - 判断日期是否为周末
安装
# 使用npm安装
npm install ./date-utils-esm
# 或使用yarn安装
yarn add ./date-utils-esm使用方法
1. 整体导入
import * as dateUtils from 'date-utils-esm';
const date = new Date();
console.log(dateUtils.formatDate(date)); // 输出: YYYY-MM-DD
console.log(dateUtils.timeAgo(date)); // 输出: 刚刚2. 按需导入
import { formatDate, timeAgo, getWeekday } from 'date-utils-esm';
const date = new Date('2024-02-15');
// 使用日期格式化
console.log(formatDate(date)); // 输出: 2024-02-15
console.log(formatDate(date, 'YYYY/MM/DD HH:mm:ss')); // 输出: 2024/02/15 00:00:00
// 使用相对时间
console.log(timeAgo(date)); // 输出: 相对时间
// 使用获取星期几
console.log(getWeekday(date, true)); // 输出: 星期四3. 在不同框架中的使用
Vue
<template>
<div>
<p>{{ formatDate(currentDate) }}</p>
<p>{{ timeAgo(currentDate) }}</p>
<p>{{ getWeekday(currentDate, true) }}</p>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { formatDate, timeAgo, getWeekday } from 'date-utils-esm';
const currentDate = ref(new Date());
</script>React
import React from 'react';
import { formatDate, timeAgo, getWeekday } from 'date-utils-esm';
function App() {
const currentDate = new Date();
return (
<div>
<p>{formatDate(currentDate)}</p>
<p>{timeAgo(currentDate)}</p>
<p>{getWeekday(currentDate, true)}</p>
</div>
);
}
export default App;Angular
import { Component } from '@angular/core';
import { formatDate, timeAgo, getWeekday } from 'date-utils-esm';
@Component({
selector: 'app-root',
template: `
<p>{{ formatDate(currentDate) }}</p>
<p>{{ timeAgo(currentDate) }}</p>
<p>{{ getWeekday(currentDate, true) }}</p>
`
})
export class AppComponent {
currentDate = new Date();
formatDate = formatDate;
timeAgo = timeAgo;
getWeekday = getWeekday;
}测试
运行测试命令:
npm test项目结构
date-utils-esm/
├── src/
│ ├── formatDate.js # 日期格式化
│ ├── timeAgo.js # 相对时间
│ ├── getWeekday.js # 获取星期几
│ ├── addDate.js # 日期加减
│ ├── dateDiff.js # 日期差计算
│ ├── isLeapYear.js # 判断闰年
│ ├── getDaysInMonth.js # 获取当月天数
│ ├── timestampToDate.js # 时间戳转换
│ ├── isSameDay.js # 日期比较
│ ├── getQuarter.js # 获取季度
│ ├── getMonthStartEnd.js # 获取月份起止
│ ├── isWeekend.js # 周末判断
│ └── index.js # 统一导出
├── test.js # 测试文件
├── package.json # 项目配置
└── README.md # 项目说明许可证
MIT
