如何以AM / PM格式显示时间 [英] How can I display time in AM/PM format

查看:821
本文介绍了如何以AM / PM格式显示时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以AM / PM格式显示时间。
示例:9:00 AM
我也想执行加减运算。我的活动将始终从9:00 AM开始。我想增加分钟来获取结果时间表事件。
除了设置自定义时间课程外,我还能怎么做?

I wanted to display time in AM / PM format. Example : 9:00 AM I wanted to perform addition subtraction operation as well. My event will start from 9:00 AM all time. I wanted to add minutes to get the result schedule event. How can I do that other then making a custom Time class?

开始9:00 AM
添加45分钟,添加后
开始时间9:45 AM

Start 9:00 AM Add 45 min, after addition Start Time 9:45 AM

推荐答案

SimpleDateFormat ,这将允许您解析和格式化时间值,例如...

Start with a SimpleDateFormat, this will allow you parse and format time values, for example...

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
    // Get the start time..
    Date start = sdf.parse("09:00 AM");
    System.out.println(sdf.format(start));
} catch (ParseException ex) {
    ex.printStackTrace();
}

有了这个,您就可以使用 Calendar ,您可以使用它来操作日期值的各个字段...

With this, you can then use Calendar with which you can manipulate the individual fields of a date value...

Calendar cal = Calendar.getInstance();
cal.setTime(start);
cal.add(Calendar.MINUTE, 45);
Date end = cal.getTime();

并将它们放在一起...

And putting it all together...

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
    Date start = sdf.parse("09:00 AM");
    Calendar cal = Calendar.getInstance();
    cal.setTime(start);
    cal.add(Calendar.MINUTE, 45);
    Date end = cal.getTime();

    System.out.println(sdf.format(start) + " to " + sdf.format(end));
} catch (ParseException ex) {
    ex.printStackTrace();
}

输出 09:00 AM至09:45 AM

已更新

或者您可以使用 JodaTime ...

Or you could use JodaTime...

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2).appendLiteral(":").appendMinuteOfHour(2).appendLiteral(" ").appendHalfdayOfDayText().toFormatter();
LocalTime start = LocalTime.parse("09:00 am", dtf);
LocalTime end = start.plusMinutes(45);

System.out.println(start.toString("hh:mm a") + " to " + end.toString("hh:mm a"));

或者,如果您使用的是Java 8,则使用新的日期/时间API ...

Or, if you're using Java 8's, the new Date/Time API...

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("hh:mm a").toFormatter();
LocalTime start = LocalTime.of(9, 0);
LocalTime end = start.plusMinutes(45);

System.out.println(dtf.format(start) + " to " + dtf.format(end));

这篇关于如何以AM / PM格式显示时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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