java mm框架_java – 格式的解析时间hh:mm:ss

根据Basil Bourque的评论,考虑到Java 8的新API,这是这个问题的更新答案:

String myDateString = "13:24:40";

LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));

int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);

int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);

int second = localTime.get(ChronoField.SECOND_OF_MINUTE);

//prints "hour: 13, minute: 24, second: 40":

System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));

备注:

>由于OP的问题包含仅包含小时,分钟和秒(没有日,月等)的时间瞬间的具体示例,上面的答案仅使用LocalTime.如果想要解析也包含天,月的字符串,等等,然后需要LocalDateTime.它的用法非常类似于LocalTime.

>由于时间瞬间int OP的问题不包含任何有关时区的信息,答案使用LocalXXX版本的日期/时间类(LocalTime,LocalDateTime).如果需要解析的时间字符串也包含时区信息,则需要使用ZonedDateTime.

======以下是此问题的旧(原始)答案,使用pre-Java8 API:=====

我很抱歉,如果我对这个人感到不安,但我真的要回答这个问题. Java API非常庞大,我认为有人可能会偶尔错过一个.

SimpleDateFormat可以在这里做到这一点:

它应该是这样的:

String myDateString = "13:24:40";

//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

Date date = sdf.parse(myDateString);

Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance

calendar.setTime(date); // assigns calendar to given date

int hour = calendar.get(Calendar.HOUR);

int minute; /... similar methods for minutes and seconds

你应该知道的陷阱:

>传递给SimpleDateFormat的模式可能与我的示例中的模式不同,具体取决于您拥有的值(12小时格式或24小时格式的小时数等).请查看链接中的文档以获取详细信息

>一旦你从你的String创建一个Date对象(通过SimpleDateFormat),不要试图使用Date.getHour(),Date.getMinute()等.它们似乎有时会工作,但总的来说它们可以给出错误结果,因此现在已弃用.请使用日历,如上例所示.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值