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

如何使用java.time的DateTimeFormatter格式化解析上午/下午/夜间时段?

解决方案:使用模式字母B

java.time API确实支持通过DateTimeFormatter格式化出in the morning这类自然语言时段,核心是使用模式字母**B**——它专门用于表示一天中的时段(period of day),不同的字母数量对应不同格式风格:

  • B/BB:短格式(如morning)
  • BBB/BBBB:长格式(如in the morning)
  • BBBBB:窄格式(如AM)

针对你的需求,直接用BBBB作为模式即可实现预期效果:

final DateTimeFormatter FORMATTER = DateTimeFormatter
                                        .ofPattern("BBBB", Locale.ENGLISH);

// 输出:in the morning
System.out.println(LocalTime.of(8, 20, 30).format(FORMATTER)); 

// 输出:in the evening
System.out.println(LocalTime.of(20, 20, 30).format(FORMATTER));

关于解析支持

如果需要反向解析这类文本到LocalTime,DateTimeFormatter也支持基于B模式的解析:

  • 解析会将时段映射到该时段的默认时间(比如in the morning对应上午9点左右,具体依赖Locale定义)
  • 若要自定义解析后的时间或时段划分,可通过DateTimeFormatterBuilder扩展逻辑,示例如下:
// 自定义时段到默认时间的映射
Map<String, LocalTime> periodToTime = new HashMap<>();
periodToTime.put("in the morning", LocalTime.of(8, 0));
periodToTime.put("in the afternoon", LocalTime.of(14, 0));
periodToTime.put("in the evening", LocalTime.of(20, 0));
periodToTime.put("at night", LocalTime.of(23, 0));

DateTimeFormatter parser = new DateTimeFormatterBuilder()
        .appendText(ChronoField.PERIOD_OF_DAY, TextStyle.FULL)
        .toFormatter(Locale.ENGLISH)
        .withResolverStyle(ResolverStyle.SMART);

// 解析示例:得到LocalTime.of(8,0)
LocalTime morningTime = LocalTime.parse("in the morning", parser);

自定义时段划分(可选)

如果内置的时段划分不符合你的需求(比如调整morning/afternoon的时间节点),可以通过自定义逻辑实现:

// 自定义时段判断逻辑
private static String getCustomPeriod(LocalTime time) {
    int hour = time.getHour();
    if (hour >= 5 && hour < 12) {
        return "in the morning";
    } else if (hour >= 12 && hour < 17) {
        return "in the afternoon";
    } else if (hour >= 17 && hour < 23) {
        return "in the evening";
    } else {
        return "at night";
    }
}

// 构建自定义格式化器
DateTimeFormatter customFormatter = new DateTimeFormatterBuilder()
        .append((temporal, appendable) -> {
            appendable.append(getCustomPeriod(LocalTime.from(temporal)));
        })
        .toFormatter(Locale.ENGLISH);

// 使用示例
System.out.println(LocalTime.of(7, 30).format(customFormatter)); // in the morning
System.out.println(LocalTime.of(18, 0).format(customFormatter)); // in the evening

内容的提问来源于stack exchange,提问作者Arvind Kumar Avinash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 10:42:26