java 时间 pm_编写一个java程序用以将AM/PM格式的时间转换为24小时格式,求大神完成代码...

SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String strCurrentTime = objSDateFormat.format(Date类型的时间);

注:大写的HH为24小时制,小写的hh为12小时制,当然还可以在ss的后面加上 a,这样可以在后面显示上下文:显示效果为“2008-03-24 17:00:14 下午”

这个更全

实现思路就是输入一个时间,之后会输出相应的12小时和24小时效果展示:

import java.text.SimpleDateFormat;

import java.util.Locale;

import java.util.Scanner;

public class App {

public static void main(String[] args) {

while (true) {

System.out.println("Enter time in 24-hour notation:");

Scanner sc = new Scanner(System.in);

String line = sc.nextLine();

try {

outTime(line);

} catch (TimeFormatException e) {

System.out.println("There is no such time as " + line);

System.out.println("Try again:");

continue;

}

sc = new Scanner(System.in);

line = sc.nextLine();

if ("n".equalsIgnoreCase(line)) {

break;

}

}

System.out.println("End of program");

}

public static void outTime(String line) throws TimeFormatException {

SimpleDateFormat _24time = new SimpleDateFormat("HH:mm");

SimpleDateFormat _12time = new SimpleDateFormat("hh:mm a",

Locale.ENGLISH);

try {

String[] array = line.split(":");

if (Integer.parseInt(array[0]) < 0

|| Integer.parseInt(array[0]) > 23) {

throw new TimeFormatException();

}

if (Integer.parseInt(array[1]) < 0

|| Integer.parseInt(array[1]) > 59) {

throw new TimeFormatException();

}

System.out.println(_12time.format(_24time.parse(line)));

System.out.println("Again?(y/n)");

} catch (Exception e) {

throw new TimeFormatException();

}

}

}

class TimeFormatException extends Exception {

}

取消

评论

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值