Formatting Time as Chinese Text in Java
Retrieving and Formatting Time in Chinese Using Java
Java provides multiple modern and legacy APIs for handling time. To display the current hour, minute, and second in Chinese characters (e.g., "14时35分22秒"), developers can choose between java.time and java.text approaches.
Modern Approach with LocalTime and DateTimeFormatter
The java.time package offers thread-safe, immutable time representations. Use LocalTime.now() to fetch the current time of day, then apply a custom DateTimeFormatter with Chinese locale-aware patterns:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class ChineseTimeFormatter {
public static void main(String[] args) {
LocalTime now = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH'时'mm'分'ss'秒'", Locale.CHINA);
String formatted = now.format(formatter);
System.out.println("当前时间(中文格式):" + formatted);
}
}
This approach avoids deprecated Date/SimpleDateFormat usage and leverages immutable formatting rules.
Legacy Approach with SimpleDateFormat
For compatibility with older codebases, SimpleDateFormat remains viable. Note that it is not thread-safe and requires explicit locale configuration:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class LegacyChineseTime {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH'时'mm'分'ss'秒'", Locale.CHINA);
String result = sdf.format(now);
System.out.println("中文时间字符串:" + result);
}
}
Both examples produce output like 15时08分47秒, using literal Chinese characters inside single quotes in the pattern string to prevent interpretation as format tokens.
Key Considerations
- Prefer
DateTimeFormatteroverSimpleDateFormatfor new development due to immutability and safety. - The pattern
HH'时'mm'分'ss'秒'explicitly escapes Chinese literals — noLocaledependency is required for the literals themselves, butLocale.CHINAensures proper digit rendering in some contexts (e.g., full-width numerals if configured). - Avoid relying on system default locale; always specify
Locale.CHINAorLocale.SIMPLIFIED_CHINESEfor consistency.