Quasar企业级日期格式化工具函数设计
# 企业级日期格式化工具函数设计
我将为您设计一个企业级的日期格式化工具函数,基于Quasar的date工具,默认使用当前日期,并输出包含星期的格式化字符串。
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>企业级日期格式化工具</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/quasar@2.10.2/dist/quasar.prod.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@3.2.31/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/quasar@2.10.2/dist/quasar.umd.prod.js"></script>
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #f8fafc;
color: #334155;
padding: 20px;
line-height: 1.6;
}
.container {
max-width: 1000px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
padding: 30px;
}
.header {
text-align: center;
margin-bottom: 40px;
}
h1 {
color: #1e293b;
font-weight: 600;
margin-bottom: 10px;
}
.subtitle {
color: #64748b;
font-size: 1.1rem;
}
.example-section {
margin-bottom: 50px;
padding: 25px;
border-radius: 8px;
background: #f1f5f9;
}
.example-title {
font-size: 1.3rem;
color: #334155;
margin-bottom: 20px;
font-weight: 500;
display: flex;
align-items: center;
}
.example-title i {
margin-right: 10px;
color: #3b82f6;
}
.code-block {
background: #1e293b;
color: #e2e8f0;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
margin: 20px 0;
font-family: 'Fira Code', monospace;
font-size: 0.9rem;
}
.preview {
background: white;
padding: 25px;
border-radius: 8px;
margin: 20px 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.note {
background: #fef3c7;
border-left: 4px solid #f59e0b;
padding: 15px;
margin: 20px 0;
border-radius: 4px;
color: #92400e;
}
.footer {
text-align: center;
margin-top: 50px;
color: #64748b;
font-size: 0.9rem;
}
.demo-output {
padding: 15px;
background: #e0f2fe;
border-radius: 8px;
margin: 15px 0;
font-family: 'Fira Code', monospace;
}
.function-demo {
margin-top: 30px;
}
.input-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #374151;
}
.output-group {
margin-top: 25px;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<div class="header">
<h1>企业级日期格式化工具函数</h1>
<p class="subtitle">基于Quasar Date工具的高级日期格式化实现</p>
</div>
<div class="example-section">
<div class="example-title">
<i>las la-info-circle</i>
<span>工具函数实现</span>
</div>
<div class="note">
以下是一个完整的企业级日期格式化工具函数,使用TypeScript实现,支持多种日期格式和本地化。
</div>
<div class="code-block">
// /src/utils/dateFormatter.ts
import { date } from 'quasar';
/**
* 日期格式化选项接口
*/
export interface DateFormatOptions {
/**
* 日期格式字符串
* @default 'YYYY-MM-DD HH:mm:ss dddd'
*/
format?: string;
/**
* 本地化语言代码
* @default 'zh-CN'
*/
locale?: string;
/**
* 是否包含星期
* @default true
*/
includeWeekday?: boolean;
}
/**
* 星期映射配置
*/
export const WEEKDAY_MAP: Record<string, string[]> = {
'en-US': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
'zh-CN': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
'zh-TW': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
'ja-JP': ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'],
'ko-KR': ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
};
/**
* 默认日期格式化选项
*/
export const DEFAULT_OPTIONS: DateFormatOptions = {
format: 'YYYY-MM-DD HH:mm:ss',
locale: 'zh-CN',
includeWeekday: true,
};
/**
* 企业级日期格式化函数
* @param inputDate 可选,输入的日期对象、时间戳或日期字符串
* @param options 可选,格式化选项
* @returns 格式化后的日期字符串
*/
export function formatDateWithWeekday(
inputDate?: Date | number | string,
options: DateFormatOptions = {}
): string {
// 合并默认选项和用户选项
const mergedOptions: DateFormatOptions = { ...DEFAULT_OPTIONS, ...options };
const { format, locale, includeWeekday } = mergedOptions;
// 处理输入日期,默认为当前日期
const targetDate = inputDate ? new Date(inputDate) : new Date();
// 验证日期有效性
if (isNaN(targetDate.getTime())) {
throw new Error('Invalid date provided to formatDateWithWeekday');
}
// 使用Quasar格式化日期
let formattedDate = date.formatDate(targetDate, format);
// 如果需要包含星期
if (includeWeekday) {
const weekdayIndex = targetDate.getDay();
const weekdayMap = WEEKDAY_MAP[locale || 'zh-CN'] || WEEKDAY_MAP['zh-CN'];
const weekday = weekdayMap[weekdayIndex];
// 将星期添加到格式化日期中
formattedDate = `${formattedDate} ${weekday}`;
}
return formattedDate;
}
/**
* 便捷函数:获取当前日期时间带星期(中文)
* @returns 格式化后的日期字符串
*/
export function getCurrentDateTimeWithWeekday(): string {
return formatDateWithWeekday();
}
/**
* 便捷函数:获取当前日期时间带星期(英文)
* @returns 格式化后的日期字符串
*/
export function getCurrentDateTimeWithWeekdayEN(): string {
return formatDateWithWeekday(undefined, { locale: 'en-US' });
}
</div>
</div>
<div class="example-section">
<div class="example-title">
<i>las la-cog</i>
<span>使用示例</span>
</div>
<div class="preview">
<div class="function-demo">
<div class="input-group">
<label>默认格式(当前日期时间):</label>
<div class="demo-output">{{ defaultFormat }}</div>
</div>
<div class="input-group">
<label>自定义日期(2023-12-25):</label>
<div class="demo-output">{{ customDate }}</div>
</div>
<div class="input-group">
<label>英文格式:</label>
<div class="demo-output">{{ englishFormat }}</div>
</div>
<div class="input-group">
<label>时间戳格式(1700000000000):</label>
<div class="demo-output">{{ timestampFormat }}</div>
</div>
<div class="input-group">
<label>自定义格式(YYYY年MM月DD日 dddd):</label>
<div class="demo-output">{{ customFormat }}</div>
</div>
</div>
</div>
<div class="code-block">
// 在Vue组件中的使用示例
import {
formatDateWithWeekday,
getCurrentDateTimeWithWeekday,
getCurrentDateTimeWithWeekdayEN
} from '@/utils/dateFormatter';
// 默认格式(当前日期时间)
const defaultFormat = getCurrentDateTimeWithWeekday();
// 自定义日期
const customDate = formatDateWithWeekday('2023-12-25');
// 英文格式
const englishFormat = getCurrentDateTimeWithWeekdayEN();
// 时间戳格式
const timestampFormat = formatDateWithWeekday(1700000000000);
// 自定义格式
const customFormat = formatDateWithWeekday(undefined, {
format: 'YYYY年MM月DD日',
locale: 'zh-CN'
});
</div>
</div>
<div class="example-section">
<div class="example-title">
<i>las la-code</i>
<span>完整工具类实现</span>
</div>
<div class="note">
对于更复杂的企业级应用,可以创建一个完整的日期工具类,提供更多日期操作功能。
</div>
<div class="code-block">
// /src/utils/dateUtils.ts
import { date } from 'quasar';
import {
DateFormatOptions,
WEEKDAY_MAP,
DEFAULT_OPTIONS
} from './dateFormatter';
/**
* 企业级日期工具类
*/
export class DateUtils {
/**
* 格式化日期带星期
* @param inputDate 可选,输入的日期对象、时间戳或日期字符串
* @param options 可选,格式化选项
* @returns 格式化后的日期字符串
*/
static formatWithWeekday(
inputDate?: Date | number | string,
options: DateFormatOptions = {}
): string {
const mergedOptions: DateFormatOptions = { ...DEFAULT_OPTIONS, ...options };
const { format, locale, includeWeekday } = mergedOptions;
const targetDate = inputDate ? new Date(inputDate) : new Date();
if (isNaN(targetDate.getTime())) {
throw new Error('Invalid date provided to formatWithWeekday');
}
let formattedDate = date.formatDate(targetDate, format);
if (includeWeekday) {
const weekdayIndex = targetDate.getDay();
const weekdayMap = WEEKDAY_MAP[locale || 'zh-CN'] || WEEKDAY_MAP['zh-CN'];
const weekday = weekdayMap[weekdayIndex];
formattedDate = `${formattedDate} ${weekday}`;
}
return formattedDate;
}
/**
* 获取日期开始时间(00:00:00)
* @param inputDate 可选,输入的日期
* @returns 日期开始时间
*/
static getStartOfDay(inputDate?: Date | number | string): Date {
const targetDate = inputDate ? new Date(inputDate) : new Date();
return date.startOfDate(targetDate, 'day');
}
/**
* 获取日期结束时间(23:59:59)
* @param inputDate 可选,输入的日期
* @returns 日期结束时间
*/
static getEndOfDay(inputDate?: Date | number | string): Date {
const targetDate = inputDate ? new Date(inputDate) : new Date();
const endOfDay = date.endOfDate(targetDate, 'day');
return endOfDay;
}
/**
* 计算日期差
* @param date1 第一个日期
* @param date2 第二个日期
* @param unit 时间单位
* @returns 日期差值
*/
static getDateDiff(
date1: Date | number | string,
date2: Date | number | string,
unit: 'days' | 'hours' | 'minutes' | 'seconds' = 'days'
): number {
const d1 = new Date(date1);
const d2 = new Date(date2);
const diffMs = Math.abs(d1.getTime() - d2.getTime());
switch (unit) {
case 'days':
return Math.floor(diffMs / (1000 * 60 * 60 * 24));
case 'hours':
return Math.floor(diffMs / (1000 * 60 * 60));
case 'minutes':
return Math.floor(diffMs / (1000 * 60));
case 'seconds':
return Math.floor(diffMs / 1000);
default:
return diffMs;
}
}
/**
* 添加时间到日期
* @param inputDate 输入日期
* @param amount 要添加的数量
* @param unit 时间单位
* @returns 新日期
*/
static addToDate(
inputDate: Date | number | string,
amount: number,
unit: 'days' | 'months' | 'years' | 'hours' | 'minutes'
): Date {
const targetDate = new Date(inputDate);
switch (unit) {
case 'days':
targetDate.setDate(targetDate.getDate() + amount);
break;
case 'months':
targetDate.setMonth(targetDate.getMonth() + amount);
break;
case 'years':
targetDate.setFullYear(targetDate.getFullYear() + amount);
break;
case 'hours':
targetDate.setHours(targetDate.getHours() + amount);
break;
case 'minutes':
targetDate.setMinutes(targetDate.getMinutes() + amount);
break;
}
return targetDate;
}
/**
* 检查日期是否在范围内
* @param date 要检查的日期
* @param startDate 开始日期
* @param endDate 结束日期
* @returns 是否在范围内
*/
static isDateInRange(
date: Date | number | string,
startDate: Date | number | string,
endDate: Date | number | string
): boolean {
const d = new Date(date).getTime();
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
return d >= start && d <= end;
}
/**
* 获取日期所在的周范围
* @param inputDate 输入日期
* @param startOfWeek 一周的开始日(0-6,0表示周日)
* @returns 周的起始和结束日期
*/
static getWeekRange(
inputDate?: Date | number | string,
startOfWeek: number = 0
): { start: Date; end: Date } {
const targetDate = inputDate ? new Date(inputDate) : new Date();
const dayOfWeek = targetDate.getDay();
// 计算到周开始日的差值
let diff = dayOfWeek - startOfWeek;
if (diff < 0) diff += 7;
const start = new Date(targetDate);
start.setDate(targetDate.getDate() - diff);
start.setHours(0, 0, 0, 0);
const end = new Date(start);
end.setDate(start.getDate() + 6);
end.setHours(23, 59, 59, 999);
return { start, end };
}
}
</div>
</div>
<div class="example-section">
<div class="example-title">
<i>las la-check-circle</i>
<span>单元测试示例</span>
</div>
<div class="note">
企业级代码应该包含完整的单元测试,确保功能的正确性和可靠性。
</div>
<div class="code-block">
// /tests/utils/dateFormatter.spec.ts
import { describe, it, expect } from 'vitest';
import { formatDateWithWeekday, DateFormatOptions } from '@/utils/dateFormatter';
describe('日期格式化工具', () => {
it('应该使用默认选项格式化当前日期', () => {
const result = formatDateWithWeekday();
// 验证结果包含日期时间和星期
expect(result).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} 星期/);
});
it('应该正确格式化指定日期', () => {
// 2023年1月1日是星期日
const result = formatDateWithWeekday('2023-01-01');
expect(result).toContain('2023-01-01');
expect(result).toContain('星期日');
});
it('应该支持英文格式', () => {
const options: DateFormatOptions = {
locale: 'en-US'
};
// 2023年1月1日是星期日
const result = formatDateWithWeekday('2023-01-01', options);
expect(result).toContain('2023-01-01');
expect(result).toContain('Sunday');
});
it('应该支持自定义格式', () => {
const options: DateFormatOptions = {
format: 'YYYY/MM/DD',
includeWeekday: true
};
const result = formatDateWithWeekday('2023-01-01', options);
expect(result).toContain('2023/01/01');
expect(result).toContain('星期日');
});
it('应该处理时间戳输入', () => {
// 2023年1月1日 00:00:00的时间戳
const timestamp = 1672531200000;
const result = formatDateWithWeekday(timestamp);
expect(result).toContain('2023-01-01');
});
it('应该处理无效日期输入', () => {
expect(() => {
formatDateWithWeekday('invalid-date');
}).toThrow('Invalid date provided');
});
});
</div>
</div>
<div class="footer">
<p>© 2023 企业级日期格式化工具 | 使用Quasar v2.10.2</p>
</div>
</div>
</div>
<script>
const { createApp, ref, onMounted } = Vue;
// 模拟日期格式化工具函数
const formatDateWithWeekday = (inputDate, options = {}) => {
const mergedOptions = {
format: 'YYYY-MM-DD HH:mm:ss',
locale: 'zh-CN',
includeWeekday: true,
...options
};
const targetDate = inputDate ? new Date(inputDate) : new Date();
if (isNaN(targetDate.getTime())) {
throw new Error('Invalid date provided');
}
// 使用Quasar的date.formatDate(这里简化实现)
const formatMap = {
'YYYY': targetDate.getFullYear(),
'MM': String(targetDate.getMonth() + 1).padStart(2, '0'),
'DD': String(targetDate.getDate()).padStart(2, '0'),
'HH': String(targetDate.getHours()).padStart(2, '0'),
'mm': String(targetDate.getMinutes()).padStart(2, '0'),
'ss': String(targetDate.getSeconds()).padStart(2, '0'),
};
let formattedDate = mergedOptions.format;
for (const [key, value] of Object.entries(formatMap)) {
formattedDate = formattedDate.replace(key, value);
}
if (mergedOptions.includeWeekday) {
const weekdays = {
'en-US': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
'zh-CN': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
};
const weekdayMap = weekdays[mergedOptions.locale] || weekdays['zh-CN'];
const weekday = weekdayMap[targetDate.getDay()];
formattedDate = `${formattedDate} ${weekday}`;
}
return formattedDate;
};
const app = createApp({
setup() {
const defaultFormat = ref('');
const customDate = ref('');
const englishFormat = ref('');
const timestampFormat = ref('');
const customFormat = ref('');
onMounted(() => {
defaultFormat.value = formatDateWithWeekday();
customDate.value = formatDateWithWeekday('2023-12-25');
englishFormat.value = formatDateWithWeekday(undefined, { locale: 'en-US' });
timestampFormat.value = formatDateWithWeekday(1700000000000);
customFormat.value = formatDateWithWeekday(undefined, {
format: 'YYYY年MM月DD日',
locale: 'zh-CN'
});
});
return {
defaultFormat,
customDate,
englishFormat,
timestampFormat,
customFormat
};
}
});
app.use(Quasar);
app.mount('#app');
</script>
</body>
</html>
```
## 设计说明
这个企业级日期格式化工具函数具有以下特点:
### 1. 类型安全
- 使用TypeScript接口定义选项参数
- 明确的输入和输出类型
- 完整的类型注释
### 2. 灵活性
- 支持多种日期输入格式(Date对象、时间戳、日期字符串)
- 可自定义输出格式
- 支持多语言星期显示
### 3. 健壮性
- 包含日期有效性验证
- 提供默认选项和错误处理
- 完整的单元测试示例
### 4. 扩展性
- 模块化设计,易于扩展新功能
- 提供便捷函数和完整工具类两种使用方式
- 支持自定义星期映射
### 5. 企业级特性
- 完整的文档注释
- 符合企业代码规范
- 提供工具类封装,包含更多日期操作功能
这个工具函数可以直接集成到您的Quasar项目中,提供了强大而灵活的日期格式化能力,同时保持了代码的健壮性和可维护性。
浙公网安备 33010602011771号