You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.5 KiB
TypeScript

/**
* 日期工具函数
*/
/**
* 获取当前日期时间,格式为 YYYY-MM-DD HH:mm:ss
* @returns {string} 格式化后的日期时间字符串
*/
export const getCurrentDateTime = (): string => {
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
/**
* 格式化日期,格式为 YYYY-MM-DD
* @param date 日期对象,默认为当前日期
* @returns {string} 格式化后的日期字符串
*/
export const formatDate = (date: Date = new Date()): string => {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
};
/**
* 格式化时间,格式为 HH:mm:ss
* @param date 日期对象,默认为当前日期
* @returns {string} 格式化后的时间字符串
*/
export const formatTime = (date: Date = new Date()): string => {
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
};