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

Android TextClock格式失效求助:指定24小时格式不生效

解决思路

1. 强制同时设置12小时和24小时格式

有些定制ROM(比如你用的LineageOS Nougat)可能会强制遵循系统的12/24小时制偏好,即使你指定了format24hours,它也可能优先使用对应模式下的格式。所以可以尝试把format12hours也设置成和format24hours一样的值,这样不管系统是12还是24小时模式,都会显示你想要的格式:

XML配置示例:

<!-- 日期TextClock -->
<TextClock
    android:id="@+id/textClockDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:format24Hours="dd/MM/yyyy"
    android:format12Hours="dd/MM/yyyy" />

<!-- 时间TextClock -->
<TextClock
    android:id="@+id/textClockTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:format24Hours="HH:mm:ss"
    android:format12Hours="HH:mm:ss" />

代码设置示例:

TextClock textClockDate = findViewById(R.id.textClockDate);
textClockDate.setFormat24Hour("dd/MM/yyyy");
textClockDate.setFormat12Hour("dd/MM/yyyy");

TextClock textClockTime = findViewById(R.id.textClockTime);
textClockTime.setFormat24Hour("HH:mm:ss");
textClockTime.setFormat12Hour("HH:mm:ss");

2. 绕过TextClock,自定义实现时间显示

如果上面的方法还是不生效,说明ROM对TextClock的修改比较彻底,这时候可以改用TextView配合Handler来手动更新时间和日期,完全控制显示格式:

代码示例:

private TextView tvDate, tvTime;
private Handler updateHandler = new Handler();
private Runnable updateRunnable = new Runnable() {
    @Override
    public void run() {
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        // 格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
        tvDate.setText(dateFormat.format(calendar.getTime()));
        // 格式化时间
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        tvTime.setText(timeFormat.format(calendar.getTime()));
        // 每秒更新一次时间
        updateHandler.postDelayed(this, 1000);
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    tvDate = findViewById(R.id.tvDate);
    tvTime = findViewById(R.id.tvTime);
    
    // 启动更新
    updateHandler.post(updateRunnable);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    // 销毁时移除回调,避免内存泄漏
    updateHandler.removeCallbacks(updateRunnable);
}

对应的XML只需要两个普通的TextView即可:

<TextView
    android:id="@+id/tvDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/tvTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

3. 检查系统Locale和区域设置

有时候系统的Locale设置可能会影响日期时间格式的解析,你可以尝试在格式化时指定明确的Locale(比如Locale.US或者你需要的区域),避免ROM的Locale配置干扰:

SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:13:58