You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中提取字符串括号内日期并转换为dd/mm/yyyy格式的方法

Angular中提取并转换日期的实现方案

这里提供两种完整的实现流程,涵盖从标题字符串中提取日期、转换为dd/mm/yyyy格式的全部步骤:

1. 提取括号内的日期范围

首先通过正则表达式匹配标题中括号内的内容,再拆分为起始和结束日期的原始字符串:

const title: string = "Import csv for User test (6 Jul 2022 - 5 Oct 2022)";
// 匹配括号内的日期片段
const dateMatch = title.match(/\((.*?)\)/);

if (dateMatch) {
  // 拆分起始和结束日期的原始字符串
  const [startRaw, endRaw] = dateMatch[1].split(' - ');
  // 此时startRaw = "6 Jul 2022",endRaw = "5 Oct 2022"
}

2. 转换为dd/mm/yyyy格式

方案一:使用Angular DatePipe(组件/服务场景推荐)

先确保所在模块已导入CommonModule(根模块默认包含),然后在组件中注入DatePipe完成格式化:

import { DatePipe } from '@angular/common';
import { Component } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  providers: [DatePipe] // 注入DatePipe
})
export class YourComponent {
  constructor(private datePipe: DatePipe) {
    const title: string = "Import csv for User test (6 Jul 2022 - 5 Oct 2022)";
    const dateMatch = title.match(/\((.*?)\)/);

    if (dateMatch) {
      const [startRaw, endRaw] = dateMatch[1].split(' - ');
      
      // 解析原始日期字符串为Date对象
      const startDate = new Date(startRaw);
      const endDate = new Date(endRaw);
      
      // 格式化为dd/mm/yyyy
      const start = this.datePipe.transform(startDate, 'dd/MM/yyyy');
      const end = this.datePipe.transform(endDate, 'dd/MM/yyyy');

      console.log(start); // 输出: "06/07/2022"
      console.log(end);   // 输出: "05/10/2022"
    }
  }
}

方案二:原生JavaScript实现(无依赖场景)

如果不想依赖Angular管道,可以自己实现日期解析和格式化函数:

// 自定义日期格式化函数
function formatToDDMMYYYY(rawDate: string): string {
  const date = new Date(rawDate);
  // 补零确保两位数
  const day = String(date.getDate()).padStart(2, '0');
  // 月份是0索引,需+1后补零
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const year = date.getFullYear();
  
  return `${day}/${month}/${year}`;
}

// 使用示例
const title: string = "Import csv for User test (6 Jul 2022 - 5 Oct 2022)";
const dateMatch = title.match(/\((.*?)\)/);

if (dateMatch) {
  const [startRaw, endRaw] = dateMatch[1].split(' - ');
  const start = formatToDDMMYYYY(startRaw);
  const end = formatToDDMMYYYY(endRaw);

  console.log(start); // "06/07/2022"
  console.log(end);   // "05/10/2022"
}

兼容性优化(可选)

如果遇到部分环境对new Date("6 Jul 2022")解析异常的情况,可以手动解析日期字符串:

// 手动解析原始日期字符串
function parseRawDate(raw: string): Date {
  const [day, monthStr, year] = raw.split(' ');
  // 月份映射表(0索引)
  const monthMap: Record<string, number> = {
    Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
    Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11
  };
  
  return new Date(Number(year), monthMap[monthStr], Number(day));
}

// 使用时替换new Date(startRaw)为parseRawDate(startRaw)即可

内容的提问来源于stack exchange,提问作者Learner1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:05:09