hh:mm a和HH:mm a之间的差异 [英] Difference between hh:mm a and HH:mm a

查看:352
本文介绍了hh:mm a和HH:mm a之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的原始代码-

String dateString = "23 Dec 2015 1:4 PM";
Locale locale = new Locale("en_US");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);
Date date = null;

try {
    date = formatter.parse(dateString);
} catch (ParseException e) {
    LOGGER.error(e);
}

String newDate = df.format(date);
System.out.println("oldDate = " + dateString);
System.out.println("newDate = " + newDate);

这是我的输出-

oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 AM

oldDate newDate AM-PM差异 c $ c>。现在,我将 DateFormat 代码更改为-

There is AM-PM difference between the oldDate and newDate. Now I changed the DateFormat code to-

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm a", locale);

我得到了预期的输出,即-

and I get the expected output, which is-

oldDate = 23 Dec 2015 1:4 PM
newDate = 23 Dec 2015 01:04 PM

我知道 HH 表示 24小时格式和 hh 表示 12小时格式。

I'm aware that HH signifies the 24 hour format and hh signifies the 12-hour format.

我的问题是

如果我使用 HH:mm a 而不是 hh:mm a ,这不应该以 24小时格式返回时间吗?

If I use HH:mm a instead of hh:mm a, shouldn't this be returning the time in 24-hour format?

(或)

如果默认为 12小时格式,则不应

If it defaults to 12-hour format, shouldn't it return respective AM/PM marker depending on the date input provided?

这只是为了我的理解。

推荐答案

更新的答案

这里的问题出在程序流

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");

简单日期格式化程序用于格式化日期对象的日期字符串,这是答案的重要部分

this simple date formatter is used to format the date string the Date object is created, here is the important part of answer

使用 HH SimpleDateFormater 而不是 hh ,认为提供的日期字符串采用 24小时格式,并且忽略 AM / PM标记此处。

As you are using HH instead of hh, the SimpleDateFormater considers that provided date string is in 24-Hour Format and simply ignores the AM/PM marker here.

从此SimpleDateFormatter构造的Date对象传递给

The Date Object from constructed from this SimpleDateFormatter is passed to the

DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm a", locale);

这就是为什么要打印

newDate = 23 Dec 2015 01:04 AM

如果更改行

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm a");

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");

一切都会顺利进行!

注意:创建语言环境时,应将语言代码传递给Locale()构造函数。 zh-CN 不是 en_us

Note : when creating a locale you should pass the language code to the Locale() constructor. en-us not en_us.

IMP :代码也在 Java 8 上进行了测试。 Java SE运行时环境(内部版本1.8.0_121-b13)

IMP : Code is tested on Java 8 also. Java(TM) SE Runtime Environment (build 1.8.0_121-b13)

这篇关于hh:mm a和HH:mm a之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆