将一串时间转换为24小时格式 [英] convert a string of time to 24 hour format

查看:294
本文介绍了将一串时间转换为24小时格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串以这种格式保存开始时间和结束时间上午8:30 - 晚上9:30 我希望能够删除 AM - PM 并将所有时间转换为24小时格式所以晚上9:30 真的是 21:30 并且两个时间都存储在两个不同的变量中,我知道如何将字符串剥离到子字符串但我不确定转换,这是我到目前为止。时间变量开始时持有上午8:30 - 下午9:30

I have a string holding a start time and an end time in this format 8:30AM - 9:30PM I want to be able to strip out the AM - and the PM and convert all the times to 24 hour format so 9:30PM would really be 21:30 and also have both the times stored in 2 different variables, I know how to strip the string into substrings but Im not sure about the conversion, this is what I have so far. the time variable starts out holding 8:30AM - 9:30PM.

String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM" 

String startTime;               
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"

String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"


推荐答案

工作代码(考虑到你设法拆分字符串):

Working code (considering that you managed to split the Strings):

public class App {
  public static void main(String[] args) {
    try {
        System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
        System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
        System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
        System.out.println(convertTo24HoursFormat("9:30PM"));  // 21:30
    } catch (ParseException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  // Replace with KK:mma if you want 0-11 interval
  private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
  // Replace with kk:mm if you want 1-24 interval
  private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");

  public static String convertTo24HoursFormat(String twelveHourTime)
        throws ParseException {
    return TWENTY_FOUR_TF.format(
            TWELVE_TF.parse(twelveHourTime));
  }
}

现在考虑一下,SimpleDateFormat H h K k 可能令人困惑。

Now that I think about it, SimpleDateFormat, H h K k can be confusing.

干杯。

这篇关于将一串时间转换为24小时格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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