Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public String test(String fulltime){
- // Kiem tra xem string time co ky tu : phan cach hay khong
- if(fulltime.indexOf(":")==-1)
- {
- throw new IllegalArgumentException("Khong hop le");
- }
- // Chia ra 2 strings - Trong do time[0] la gio, time[1] la phut
- String[] time = fulltime.split(":");
- // Kiem tra length cua 2 chuoi xem co hop le hay khong
- if(time[0].length() > 2 || time[0].length() < 1)
- {
- throw new IllegalArgumentException("Gio khong hop le");
- }
- if(time[1].length() > 2 || time[1].length() < 1)
- {
- throw new IllegalArgumentException("Phut khong hop le");
- }
- // Kiem tra gia tri gio co hop le hay khong (0-24)
- if(time[0].length()==1)
- {
- if(time[0].charAt(0) < '0' || time[0].charAt(0) > '9')
- {
- throw new IllegalArgumentException("Gio khong hop le");
- }
- }else{
- // Neu length la 2 ky tu thi kiem tra xem co hop le hay khong
- // Kiem tra ky tu dau tien (phai la 0->2 vi toi da la 24h)
- if(time[0].charAt(0) < '0' || time[0].charAt(0) > '2' )
- {
- throw new IllegalArgumentException("Gio khong hop le");
- }
- // Kiem tra ky tu thu 2 (0->9)
- if(time[0].charAt(1) < '0' || time[0].charAt(1) > '9')
- {
- throw new IllegalArgumentException("Gio khong hop le");
- }
- }
- if(Integer.parseInt(time[0]) > 23){
- throw new IllegalArgumentException("Gio khong hop le");
- }
- // Kiem tra gia tri phut co hop le hay khong
- if(time[1].length()==1)
- {
- if(time[1].charAt(0) < '0' || time[1].charAt(0) > '9')
- {
- throw new IllegalArgumentException("Gio khong hop le");
- }
- // Them so 0 vao dau neu chi dien 1 ky tu
- time[1] = "0"+time[1];
- }else{
- // Neu length la 2 ky tu thi kiem tra xem co hop le hay khong
- // Kiem tra ky tu dau tien (phai la 0->6 vi toi da la 60 phut)
- if(time[1].charAt(0) < '0' || time[1].charAt(0) > '6' )
- {
- throw new IllegalArgumentException("Phut khong hop le");
- }
- // Kiem tra ky tu thu 2 (0->9)
- if(time[1].charAt(1) < '0' || time[1].charAt(1) > '9')
- {
- throw new IllegalArgumentException("Phut khong hop le");
- }
- }
- if(Integer.parseInt(time[1]) > 59){
- throw new IllegalArgumentException("Phut khong hop le");
- }
- // Quy doi gio
- if(Integer.parseInt(time[0]) == 0 )
- {
- return "12:"+time[1]+"am";
- }else if(Integer.parseInt(time[0]) > 11 ){
- int hour = Integer.parseInt(time[0])-12;
- if(hour > 0)
- {
- return hour+":"+time[1]+"pm";
- }else{
- return time[0]+":"+time[1]+"pm";
- }
- }else{
- return time[0]+":"+time[1]+"am";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement