网站公告

本次更新:新公告样式

详细教程:vitepress.yiov.top

QQ 频道:******(无效二维码)

Skip to content

parseTime 日期格式化

更新: 1970/1/1 字数: 0 字 时长: 0 分钟

说明

parseTime 用于解析时间并格式化为指定字符串。支持输入 字符串、时间戳、Date 对象,可通过自定义模式指定格式。

🛠️ 函数签名

js
/**
 * 解析时间
 * @param {string|number|Date} time - 要解析的时间
 * @param {string} [pattern='{y}-{m}-{d} {h}:{i}:{s}'] - 格式化模式
 * @returns {string|null} - 格式化后的时间字符串,解析失败返回 null
 */
export function parseTime(time, pattern)

📌 参数

参数说明类型可选值默认值
time要解析的时间string / number / Date
pattern格式化模式(可选)string'{y}-{m}-{d} {h}:{i}:{s}'

🔄 返回值

  • string:格式化后的时间字符串。
  • null:时间无效时返回 null

📌 格式化模式

占位符说明示例
{y}年(四位数)2024
{m}月(两位数)09
{d}日(两位数)07
{h}小时(两位数)10
{i}分钟(两位数)30
{s}秒(两位数)00
{a}星期几(中文)星期六

📌 示例

基本用法

js
import { parseTime } from 'uviewos';

// 使用默认模式
console.log(parseTime('2024-09-07T10:30:00')); 
// 输出: "2024-09-07 10:30:00"

自定义格式

js
import { parseTime } from 'uviewos';

// 使用自定义模式
console.log(parseTime('2024-09-07T10:30:00', '{y}/{m}/{d} {h}:{i}'));
/**
 * 输出: "2024/09/07 10:30"
 */

// 使用带有星期几的模式
console.log(parseTime('2024-09-07T10:30:00', '{y}-{m}-{d} 星期{a} {h}:{i}:{s}'));
/**
 * 输出: "2024-09-07 星期六 10:30:00"
 */

时间戳

js
import { parseTime } from 'uviewos';

// 使用自定义模式
console.log(parseTime('2024-09-07T10:30:00', '{y}/{m}/{d} {h}:{i}'));// 10位时间戳(秒)
console.log(parseTime(1694062200)); 
// 输出: "2024-09-07 10:30:00"

// 13位时间戳(毫秒)
console.log(parseTime(1694062200000)); 
// 输出: "2024-09-07 10:30:00"

Date 对象

js
import { parseTime } from 'uviewos';

const date = new Date('2024-09-07T10:30:00');
console.log(parseTime(date)); 
// 输出: "2024-09-07 10:30:00"

无效时间

返回null

Released under the MIT License.

本站访客数 人次 本站总访问量