JavaScript / TypeScript日期格式化(dateFormat)

本文介绍了一个JavaScript函数`dateFormat()`,用于将日期时间格式化为指定字符串。函数接受日期时间值和格式化字符串作为参数,支持多种日期时间格式。示例中展示了如何使用此函数将数字时间戳和`Date`对象转换为易读的日期时间格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在线功能预览

①日期格式化函数dateFormat():

/**
 * 格式化日期时间字符串
 *
 * @param value 待格式化的日期时间值,支持数字、字符串和 Date 类型,默认为当前时间戳
 * @param format 格式化字符串,默认为'YYYY-MM-DD HH:mm:ss',支持格式化参数:YY:年,M:月,D:日,H:时,m:分钟,s:秒,SSS:毫秒
 * @returns 返回格式化后的日期时间字符串
 */
export function dateFormat(value: number | string | Date = Date.now(), format: string = 'YYYY-MM-DD HH:mm:ss'): string {
  try {
    let date: Date
    if (typeof value === 'number' || typeof value === 'string') {
      date = new Date(value)
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date')
      }
    } else {
      date = value
    }
    const padZero = (value: number, len: number = 2): string => {
      // 左侧补零函数
      return String(value).padStart(len, '0')
    }
    const replacement = (match: string) => {
      switch (match) {
        case 'YYYY':
          return padZero(date.getFullYear())
        case 'YY':
          return padZero(date.getFullYear()).slice(2, 4)
        case 'MM':
          return padZero(date.getMonth() + 1)
        case 'M':
          return String(date.getMonth() + 1)
        case 'DD':
          return padZero(date.getDate())
        case 'D':
          return String(date.getDate())
        case 'HH':
          return padZero(date.getHours())
        case 'H':
          return String(date.getHours())
        case 'mm':
          return padZero(date.getMinutes())
        case 'm':
          return String(date.getMinutes())
        case 'ss':
          return padZero(date.getSeconds())
        case 's':
          return String(date.getSeconds())
        case 'SSS':
          return padZero(date.getMilliseconds(), 3)
        default:
          return match
      }
    }
    return format.replace(/(YYYY|YY|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS)/g, replacement)
  } catch (error) {
    console.error('Error formatting date:', error)
    return ''
  }
}

②使用函数:

console.log(dateFormat(1680227496788, 'YYYY-MM-DD HH:mm:ss')) // 2023-03-31 09:51:36:788
console.log(dateFormat(new Date(), 'YYYY年MM月DD日 HH时mm分ss秒SSS毫秒')) // 2023年03月31日 09时53分41秒730毫秒
<think>好的,我需要回答用户关于如何使用DateFormat格式化日期的问题。首先,用户提到了引用[1],其中提到DateFormat类及其子类SimpleDateFormat的作用,允许格式化和解析日期。还有引用[2]中的$dateToString操作符示例,以及引用[3]中ArkTS的时间格式化方法。 用户的问题主要集中在Java的DateFormat和SimpleDateFormat,可能还涉及其他语言的例子。我需要先解释Java中的用法,包括如何创建实例、应用格式,并给出示例代码。然后可能需要提到其他场景,比如数据库中的日期格式化,如MongoDB的$dateToString,以及ArkTS中的方法,但根据引用内容,用户主要需求可能在Java方面。 要确保使用正确的LaTeX格式,行内公式用$...$,独立公式用$$...$$。但在这个问题中可能用不到数学公式,但如果有涉及时间戳转换可能需要。不过用户的问题更多是关于字符串格式,如yyyy-MM-dd。 需要分步骤说明:1. 创建实例,2. 定义模式,3. 格式化和解析。每个步骤给出代码示例。同时,检查是否有需要引用的地方,比如引用[1]中的SimpleDateFormat,引用[2]中的MongoDB例子,引用[3]的ArkTS。 然后生成相关问题,可能涉及不同语言中的日期处理,如何解析字符串,处理时区等。确保问题相关且覆盖用户可能感兴趣的方面。 最后,确保回答结构清晰,使用中文,代码语法正确,引用正确标注。</think>### 如何使用 DateFormat 格式化日期 在数据处理中,日期格式化是常见的需求,以下是不同场景下的实现方法: --- #### 1. **Java 中的 DateFormat 和 SimpleDateFormat** - **创建实例**:使用 `SimpleDateFormat` 指定日期格式模式 ```java SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ``` - **格式化日期 → 字符串** ```java Date now = new Date(); String formattedDate = sdf.format(now); // 输出示例:2023-10-05 14:30:45 ``` - **解析字符串 → 日期** ```java String dateString = "2023-10-05"; Date parsedDate = sdf.parse(dateString); ``` 若格式不匹配会抛出 `ParseException`,需处理异常[^1]。 --- #### 2. **数据库中的日期格式化(如 MongoDB)** - 使用聚合管道中的 `$dateToString`: ```javascript db.collection.aggregate([ { $project: { formattedDate: { $dateToString: { format: "%Y-%m-%d", date: "$dateField" } } } } ]) ``` 这会从字段 `dateField` 提取日期格式化为 `YYYY-MM-DD` 字符串[^2]。 --- #### 3. **ArkTS 中的时间格式化** - 调用系统 API(如 `DateTimeFormatter`): ```typescript import { DateTimeFormatter } from '@ohos/i18n'; let formatter = DateTimeFormatter.createDateTimeFormatter("yyyy-MM-dd HH:mm:ss"); let formattedDate = formatter.format(new Date()); ``` 支持自定义模式如 `yyyy` 表示年份、`MM` 表示月份[^3]。 --- #### 常见格式符号说明 | 符号 | 含义 | 示例 | |------|------------|-------------| | `yyyy` | 四位年份 | 2023 | | `MM` | 两位月份 | 10 | | `dd` | 两位日期 | 05 | | `HH` | 24小时制小时 | 14 | | `mm` | 分钟 | 30 | ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

theMuseCatcher

您的支持是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值