DateTimeFormatter
是一种区域设置敏感类型,即它的解析和格式化取决于Locale
. 选中Never use SimpleDateFormat or DateTimeFormatter without a Locale以了解更多信息。
如果您有一个 English Locale
,并且您希望输出始终为单个大小写(即大写),则可以将字符串操作与格式化字符串链接,例如
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
System.out.println(
LocalTime.now(ZoneOffset.UTC)
.format(DateTimeFormatter.ofPattern("ha", Locale.ENGLISH))
.toUpperCase()
);
}
}
示例运行的输出:
6AM
ONLINE DEMO
从Trail: Date Time了解有关现代日期时间 API *的更多信息。
* 如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请通过 desugaring 检查可用的 Java 8+ API。请注意,Android 8.0 Oreo 已经提供对java.time
.