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

DateTimeFormatter类是否缺少ofYearMonth()方法?

DateTimeFormatter 相关问题解答

有没有ofYearMonth()方法?

没错,JDK标准库中的DateTimeFormatter确实没有提供ofYearMonth()这个静态方法。不过要实现本地化的年月格式化,有两种实用的替代方案:

  • 利用ofLocalizedDate()配合格式化风格:选择FormatStyle.MEDIUM或FormatStyle.LONG这类风格,再指定区域设置,就能生成符合当地习惯的年月格式,示例代码:
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                                                    .withLocale(Locale.CHINA);
    String formattedYearMonth = formatter.format(YearMonth.now());
    
  • 自定义模式+指定区域:虽然ofPattern()本身不自带区域敏感性,但可以通过withLocale()方法为它绑定区域,让模式里的占位符适配当地的日期规则(比如当地语言的月份名称、日期分隔符),示例代码:
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM")
                                                    .withLocale(Locale.FRANCE);
    String formattedYearMonth = formatter.format(YearMonth.now());
    

关于ofPattern()的区域设置敏感性

你提到的ofPattern()本身不具备区域设置敏感性是准确的——它默认使用系统默认区域设置,且传入的模式字符串是固定格式。但通过链式调用withLocale(Locale)方法,就能让格式化规则适配指定区域的日期符号,弥补这一不足。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:28:14