← 中文资源

简体中文版本

Day Period 模式字母 B

格式化字母 B 给出比 am/pm 更细的 day period:上午、下午、傍晚、夜晚各有叫法,a 只有 am/pm 两档,面向用户的时刻显示更准确。

阅读英文原文

实现说明

Day Period 模式字母 B的核心是类 DayPeriodFormat和函数 main。

使用要点

  • 演示输出是带标签的(morning:、night:、am/pm:),每个操作都会留下自己的一行标注。

常见问题

运行「Day Period 模式字母 B」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 morning:、night:、am/pm: 标签标明各步骤。

核心语句

DateTimeFormatter.ofPattern("h B", Locale.US); // B formats the finer day period than am/pm
LocalDateTime morning = LocalDateTime.of(2026, 11, 21, 9, 15);
DateTimeFormatter amPm = DateTimeFormatter.ofPattern("h a", Locale.US);
LocalDateTime night = LocalDateTime.of(2026, 11, 21, 23, 45);

代码示例

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DayPeriodFormat {

    public static void main(String[] args) {
        DateTimeFormatter dayPeriod =
                DateTimeFormatter.ofPattern("h B", Locale.US); // B formats the finer day period than am/pm

        LocalDateTime morning = LocalDateTime.of(2026, 11, 21, 9, 15);
        LocalDateTime night = LocalDateTime.of(2026, 11, 21, 23, 45);

        System.out.println("morning: " + morning.format(dayPeriod));
        System.out.println("night:   " + night.format(dayPeriod));

        // 对照:a 只有 am/pm 两档,B 能区分 morning / afternoon / evening / night
        DateTimeFormatter amPm = DateTimeFormatter.ofPattern("h a", Locale.US);
        System.out.println("am/pm:   " + night.format(amPm));
    }
}