java am pm_SimpleDateFormat AM/PM conversion

java.time and ThreeTen Backport

DateTimeFormatter timeFormatter

= DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);

String time24Hour = "12:10:00";

LocalTime time = LocalTime.parse(time24Hour);

String time12Hour = time.format(timeFormatter);

System.out.println(time12Hour);

Output from this snippet is what you expected:

12:10 PM

Notice that your format pattern string, hh:mm a, is correct for formatting. I don’t know what you used for parsing, I suspect that your error may have been there.

I have added a locale to the formatter to control which language I get. Since AM and PM are hardly used in other languages than English, I chose Locale.ENGLISH, but please choose the locale that is right for you.

The SimpleDateFormat class that you used is notoriously troublesome and fortunately long outdated. Instead I am using java.time, the modern Java date and time API. This has the added bonus that parsing the 24 hour format goes smoothly without an explicit formatter. This is because the format you’ve got conforms with ISO 8601, the internation date and time standard. The modern classes parse (and also print) ISO 8601 format as their default.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).

On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值