以 24 小时制显示日期

Display Date in 24-hour issue

我正在开发一个简单的应用程序,我可以在其中获取当前 DateTime 并将其转换为 24-hour 格式。

代码:

  String DATE_yyyy_MM_dd_hh_mm_ss = "yyyy-MM-dd hh:mm:ss";

  String DATE_yyyy_MM_dd_HH_mm_ss  = "yyyy-MM-dd HH:mm:ss";  
  

  TextView tv=(TextView)findViewById(R.id.textView);
    
  tv.append("\n in 12-hour format: "+getDateFormatted(bootDate));
    
  tv.append("\n in 24-hour format: "+getDateFormatted2(bootDate));

  public String getDateFormatted(Date date){
    return String.valueOf(DateFormat.format(DATE_yyyy_MM_dd_hh_mm_ss, date));
}

public String getDateFormatted2(Date date){
    return String.valueOf(DateFormat.format(DATE_yyyy_MM_dd_HH_mm_ss, date));
}

问题:

它在我的设备上完美运行 Samsung Galaxy S3(Android 4.3), S4(Android 4.3) and Nexus 5(Android 4.4)。虽然我在 Huawei Ascend Y330 device(Android 4.2.2) 中 运行 的代码显示不正确。

Samsung Galaxy S3、S4 和 Nexus 5 中的屏幕截图:

华为Ascend Y330截图:

那么,到底是什么问题呢?我不明白。是android系统问题吗?还是设备问题?

任何人都有想法。

试试这个,

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

TextView tv=(TextView)findViewById(R.id.textView);
tv.append("\n in 12-hour format: " +sdf);
tv.append("\n in 24 -hour format: " +sdf2);

根据 documentation SimpleDateFormat 可以处理 24 小时格式的 'H' 但 DateFormat 需要 'k'.

Use a literal 'H' (for compatibility with SimpleDateFormat and Unicode) or 'k' (for compatibility with Android releases up to and including Jelly Bean MR-1) instead. Note that the two are incompatible.

所以this post suggested to use SimpleDateFormat instead of DateFormat. For more explanation about the differences between these two classes, you could take a look at this post.

这适用于所有设备,

static final SimpleDateFormat IN_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.US);
static final SimpleDateFormat OUT_DATE_FORMAT = new SimpleDateFormat("hh:mma", Locale.US);

/**
 * To format the time.
 *
 * @param strDate The input date in HH:mm:ss format.
 * @return The output date in hh:mma format.
 */
private String formatTime(String strDate) {
    try {
        Date date = IN_DATE_FORMAT.parse(strDate);
        return OUT_DATE_FORMAT.format(date);

    } catch (Exception e) {
        return "N/A";
    }
}

使用方法:formatTime(YOUR_TIME)