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

从本地日期时间字符串提取HH:mm格式时间(最低SDK版本19)

嘿,针对你在Android SDK 19下提取本地日期时间字符串中的HH:mm格式时间的需求,这里有两种靠谱的方案,你可以根据自己的项目情况选择:

方案一:使用原生SimpleDateFormat(无需额外依赖)

因为你的最低SDK是19,SimpleDateFormat在这个版本完全可用,操作步骤很清晰:

  • 第一步:先定义输入格式,确保它和你的原始日期时间字符串格式完全匹配,比如如果你的原始字符串是"2024-05-20 14:30:45",那输入格式就是"yyyy-MM-dd HH:mm:ss";如果是带中文的格式比如"2024年5月20日 下午2:30",就得对应调整格式符。
  • 第二步:定义输出格式为"HH:mm",用来提取我们需要的时间部分。

下面是完整的代码示例:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TimeExtractor {
    public static String extractTime(String localDateTimeStr) {
        // 这里替换成你实际的输入日期时间格式
        String inputPattern = "yyyy-MM-dd HH:mm:ss";
        String outputPattern = "HH:mm";
        
        // 指定Locale避免区域设置差异导致的解析错误
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern, Locale.getDefault());
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern, Locale.getDefault());
        
        try {
            Date date = inputFormat.parse(localDateTimeStr);
            return outputFormat.format(date);
        } catch (ParseException e) {
            // 解析失败的处理逻辑,可根据需求调整,比如返回空串或抛出异常
            e.printStackTrace();
            return "";
        }
    }
}

⚠️ 注意事项:

  • 一定要指定Locale,比如用Locale.getDefault()适配当前系统语言,或者固定为Locale.CHINA,避免因系统区域不同导致解析/格式化失败。
  • 输入格式必须和原始字符串严格匹配,哪怕是一个符号不对都会抛出ParseException,所以要先确认你的原始字符串格式细节。
方案二:使用ThreeTenABP(更安全的长期解决方案)

原生的SimpleDateFormat存在线程不安全的问题,如果你的项目中有大量日期时间处理场景,更推荐用ThreeTenABP——它是JSR-310日期时间规范的Android兼容库,支持API 9+,完全覆盖你的SDK 19需求。

步骤1:添加依赖

在你的app模块build.gradle中加入依赖:

implementation 'com.jakewharton.threetenabp:threetenabp:1.4.6'

步骤2:初始化库

在你的Application类的onCreate方法中初始化:

@Override
public void onCreate() {
    super.onCreate();
    ThreeTenABP.init(this);
}

步骤3:编写提取逻辑

import org.threeten.bp.LocalDateTime;
import org.threeten.bp.format.DateTimeFormatter;

public class TimeExtractor {
    public static String extractTime(String localDateTimeStr) {
        // 替换成你的输入日期时间格式
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("HH:mm");
        
        try {
            LocalDateTime dateTime = LocalDateTime.parse(localDateTimeStr, inputFormatter);
            return dateTime.format(outputFormatter);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

这个方案的优势在于API设计更合理,线程安全,而且和Java 8+的java.time包API几乎一致,后续升级到更高SDK版本时可以无缝切换到原生API。


内容的提问来源于stack exchange,提问作者tss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:45:11