在Java中使用SimpleDateFormat进行时间格式化 [英] Time formatting using SimpleDateFormat in java

查看:88
本文介绍了在Java中使用SimpleDateFormat进行时间格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是以hh:mm格式在网页上显示日期.但是,如果是1位数字,则不应在小时值之前显示零.

My requirement is to display date on webpage in hh:mm format. But, it should not display zero before the hour value if it is a 1-digit number.

例如-它应显示为:11:30 AM,9:15 AM,1:00 PM.

For example - It should be displayed as : 11:30 AM, 9:15 AM, 1:00 PM.

我试图解决此问题,但是这里唯一的问题是从1位数的小时值中删除多余的0.

I tried to resolve this but the only issue coming here is in removing the extra 0 from the 1-digit hour value.

输入时间的格式为hh:mm:ss.

日期值最初是一个字符串.首先将其解析为以下格式的日期

The date value is a string initially. It is parsed as date in below format first of all-

final SimpleDateFormat dfParse = new SimpleDateFormat("HH:mm:ss");
startTimeFmt = dfParse.parse(startTime);

然后将其格式化为以下格式-

Then it is formatted in below format -

final SimpleDateFormat dfFormat = new SimpleDateFormat("hh:mm a");
startTime = dfFormat.format(startTimeFmt);

推荐答案

尝试一下:

Date date = new SimpleDateFormat("hh:mm:ss").parse("07:15:45");
String newDate = new SimpleDateFormat("h:mm a").format(date);

这将打印7:15 AM

这篇关于在Java中使用SimpleDateFormat进行时间格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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