如何重新格式化日期和时间?

How can I reformat date and time?

如何将 24 小时制时间格式转换为 12 小时制时间格式?我知道这个问题已经被问过很多次了,但我的问题是不同的。我现在的时间是:

Tue Nov 07 18:44:47 GMT+05:00 2017

我只想在约会时间 6:44 下午。我试过这个:

private void convertTime(String time)
{
    try {
        final SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
        final Date dateObj = sdf.parse(time);
        System.out.println(dateObj);
        System.out.println(new SimpleDateFormat("K:mm a").format(dateObj));
    } catch (final ParseException e) {
        e.printStackTrace();
    }
}
final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");

使用 hh 将为您提供 12 小时格式和 HH 24 小时格式。有关 documentation.

的更多详细信息

编辑:

为了将日期字符串解析为 Date 对象,您的初始格式必须如下所示:

final SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss 'GMT'Z yyyy");
final Date dateObj = sdf.parse(time);

之后您可以根据需要格式化时间。

try {
    final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
    final Date dateObj = sdf.parse(time);
    System.out.println(dateObj);
    System.out.println(new SimpleDateFormat("K:mm a").format(dateObj));
} catch (final ParseException e) {
    e.printStackTrace();
}

来自 SimpleDateFormat 文档:

"h:mm a": 12:08 PM

所以你需要的格式:

I just want 6:44 pm from my date time

是:

final SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");
Date date = sdf1.parse(time);
final SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String newDateString = sdf.format(date);