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

Java中是否有现成方案将ISO 8601周期转换为多语言可读字符串?

ISO 8601周期转多语言可读格式的现成实现方案

下面是几种主流技术栈的现成解决方案,均无需自行定义周期翻译,依赖内置多语言支持:

Java(Java 8+)

利用java.time包的PeriodFormatterBuilder,内置多语言复数规则和翻译:

import java.time.Period;
import java.time.format.PeriodFormatterBuilder;
import java.util.Locale;

public class IsoPeriodFormatter {
    public static String format(String isoPeriod, Locale locale) {
        // 单独处理周,避免Period.parse将P1W转为P7D
        if (isoPeriod.matches("P\\d+W")) {
            int weeks = Integer.parseInt(isoPeriod.substring(1, isoPeriod.length() - 1));
            return new PeriodFormatterBuilder()
                    .appendWeeks()
                    .appendSuffix(" Week", " Weeks")
                    .toFormatter(locale)
                    .format(Period.ofWeeks(weeks));
        }
        
        // 处理年、月、日等其他周期
        Period period = Period.parse(isoPeriod);
        return new PeriodFormatterBuilder()
                .appendYears().appendSuffix(" Year", " Years")
                .appendMonths().appendSuffix(" Month", " Months")
                .appendDays().appendSuffix(" Day", " Days")
                .toFormatter(locale)
                .format(period);
    }

    public static void main(String[] args) {
        System.out.println(format("P1W", Locale.ENGLISH)); // 1 Week
        System.out.println(format("P2W", Locale.ENGLISH)); // 2 Weeks
        System.out.println(format("P1W", new Locale("pl"))); // 1 Tydzień
        System.out.println(format("P2W", new Locale("pl"))); // 2 Tygodnie
    }
}

Python

依赖python-dateutil解析周期,babel处理多语言格式化:

from dateutil.relativedelta import relativedelta
from babel.dates import format_timedelta

def format_iso_period(iso_period: str, locale: str) -> str:
    period_str = iso_period.lstrip('P')
    weeks = int(period_str.split('W')[0]) if 'W' in period_str else 0
    remaining = period_str.split('W')[-1] if 'W' in period_str else period_str
    
    years = int(remaining.split('Y')[0]) if 'Y' in remaining else 0
    remaining = remaining.split('Y')[-1] if 'Y' in remaining else remaining
    
    months = int(remaining.split('M')[0]) if 'M' in remaining else 0
    days = int(remaining.split('D')[0]) if 'D' in remaining else 0
    
    delta = relativedelta(years=years, months=months, days=days, weeks=weeks)
    return format_timedelta(delta, locale=locale, format='long')

# 示例调用
print(format_iso_period('P1W', 'en'))  # 1 week
print(format_iso_period('P2W', 'en'))  # 2 weeks
print(format_iso_period('P1W', 'pl'))  # 1 tydzień
print(format_iso_period('P2W', 'pl'))  # 2 tygodnie

安装依赖:pip install python-dateutil babel

JavaScript/TypeScript

使用luxon库,内置多语言支持,自动处理复数和翻译:

import { Duration } from 'luxon';

function formatIsoPeriod(isoPeriod, locale) {
    const duration = Duration.fromISO(isoPeriod);
    // toHuman方法自动生成符合语言习惯的可读文本
    return duration.toHuman({ locale });
}

// 示例调用
console.log(formatIsoPeriod('P1W', 'en')); // 1 week
console.log(formatIsoPeriod('P2W', 'en')); // 2 weeks
console.log(formatIsoPeriod('P1W', 'pl')); // 1 tydzień
console.log(formatIsoPeriod('P2W', 'pl')); // 2 tygodnie

安装依赖:npm install luxon

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:20:43