如何在Android中将12小时制的日期转换为24小时制?

4

你好,我有一些日期数据,例如...

String date="09:00 AM"

但我需要09:00:00

所以我使用以下方法。

 String date="09:00 AM"  
 SimpleDateFormat f1 = new SimpleDateFormat("hh:mm:ss");
 Date d1= f1.parse(date);

但是它给我抛出了解析异常。

请帮助我找到原因。

提前感谢。

2个回答

8

这并不是正确的日期解析格式,你需要像这样:

"hh:mm a"

一旦您拥有日期对象,您可以使用不同的格式将其输出。以下代码段显示如何实现:

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

String date = "09:27 PM";

SimpleDateFormat h_mm_a   = new SimpleDateFormat("h:mm a");
SimpleDateFormat hh_mm_ss = new SimpleDateFormat("HH:mm:ss");

try {
    Date d1 = h_mm_a.parse(date);
    System.out.println (hh_mm_ss.format(d1));
} catch (Exception e) {
    e.printStackTrace();
}

这将输出:
21:27:00

正如您所期望的那样。

0
Date c = Calendar.getInstance().getTime();

//day of the month

//EEEE---full day name
//EEE- 3 chars of the day
SimpleDateFormat outFormat = new SimpleDateFormat("EEE");
String dayof_month = outFormat.format(c);

//date
//MMM--3 chars of month name
//MM--number of the month
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

//time
//hh---12 hrs format
//HH---24 hrs format
// a stands for AM/PM
DateFormat date = new SimpleDateFormat("hh:mm:ss a");
String localTime = date.format(c);

login_date_text.setText(dayof_month +" , "+formattedDate);
login_time_text.setText(localTime);

Log.e("testing","date ==" +dayof_month +" , "+formattedDate);
Log.e("testing","time ==" +localTime);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接