For AI agents: the complete documentation index is available at /tc39-atlas/llms.txt, the full documentation bundle is available at /tc39-atlas/llms-full.txt, and this page is available as Markdown at /tc39-atlas/proposals/intl-datetimeformat-prototype-formattoparts.md.
  • 简体中文
  • Intl.DateTimeFormat.prototype.formatToParts S4

    提案概览
    提案速览

    该提案为 Intl.DateTimeFormat 和 Intl.NumberFormat 添加了 formatToParts 方法,使开发者能够访问格式化字符串的各个组成部分(如月份、货币、数字),以便进行区域设置感知的自定义。

    Note

    以下 README 来自上游仓库,其中的阶段或状态标注可能滞后;当前信息以提案概览为准。

    DateTimeFormat.prototype.formatToParts / NumberFormat.prototype.formatToParts

    关于 DateTimeFormat.prototype.formatToParts 和 NumberFormat.prototype.formatToParts 的提案、规范、测试和参考实现。

    状态

    第 4 阶段

    实现进度

    • Polyfill
    • Gecko 的补丁

    反向链接

    作者

    • Caridy Patiño (@caridy)
    • Eric Ferraiuolo (@ericf)
    • Zibi Braniecki (@zbraniecki)

    审阅者

    待定

    说明性内容

    该提案支持对 Intl 格式化器产生的字符串进行区域设置感知的格式化。

    用法

    
    let dateFormatter = Intl.DateTimeFormat('en', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    let now = new Date();
    
    let dateStr = dateFormatter.formatToParts(now).map(({type, value}) => {
      switch (type) {
        case 'month': return `<b>${value}</b>`;
        default     : return value;
      }
    }).reduce((string, part) => string + part);
    
    console.log(dateFormatter.format(now)); // yields "November 23, 2015"
    console.log(dateStr); // yields "<b>November</b> 23, 2015"
    
    
    let numFormatter = Intl.NumberFormat('en', {
      style: 'currency',
      currency: 'EUR',
    });
    let amount = -1000;
    
    let numStr = numFormatter.formatToParts(amount).map(({type, value}) => {
      switch (type) {
        case 'currency': return `<b>${value}</b>`;
        case 'number'  : return `<i>${value}</i>`;
        default        : return value;
      }
    }).reduce((string, part) => string + part);
    
    console.log(numFormatter.format(amount)); // yields "-€1,000.00"
    console.log(numStr); // yields "-<b>€</b><i>1,000.00</i>"