Java中如何将秒数转换为HH:MM格式(不含秒数)
Great question! Since you're already using DateUtils.formatElapsedTime() for HH:MM:SS formatting, let's stick with Android's built-in tools as much as possible to avoid rolling your own logic.
Unfortunately, there's no direct out-of-the-box utility function in DateUtils that outputs an HH:MM format (truncating seconds) right away. But we can combine existing official tools with minimal, safe processing to get exactly what you need:
Option 1: Compatible with all Android API levels
This approach leverages DateUtils to handle the core formatting, then trims off the seconds part with simple string operations:
long totalSeconds = 3665; // Truncate seconds by rounding down to the nearest minute long roundedToMinutes = totalSeconds - (totalSeconds % 60); // Generate the full HH:MM:SS string using DateUtils String hhmmss = DateUtils.formatElapsedTime(roundedToMinutes); // Remove the seconds segment to get HH:MM String hhmm = hhmmss.substring(0, hhmmss.lastIndexOf(':')); // Optional: Remove leading zero from hours (e.g., "01:01" → "1:01") hhmm = hhmm.replaceFirst("^0+(?=\\d)", "");
This keeps you relying on DateUtils's tested localization and formatting logic, with only trivial string manipulation.
Option 2: API 26+ (Java 8 Time API)
If you're targeting Android 8.0 (API 26) or higher, you can use the standard Java Time API for a cleaner, more direct solution:
long totalSeconds = 3665; Duration duration = Duration.ofSeconds(totalSeconds); // Format hours (without leading zeros) and minutes (two digits) String hhmm = String.format("%d:%02d", duration.toHours(), duration.toMinutesPart());
This avoids DateUtils entirely but uses official, well-maintained standard library tools.
Both options prioritize using existing utility/standard libraries over writing custom time formatting logic from scratch, which aligns with your request.
内容的提问来源于stack exchange,提问作者Magnus

