2019-07-17

시간 문자열 조정하기

시간 문자열 조정하기

목표

“PM 12:01:00” 형태의 문자열 time 과 증가될 초인 sec를 합쳐 24시간 표기법으로 전환한다

“PM 11:01:00”, 10 => “23:01:10”
“AM 05:01:00”, 100 => “05:02:40”

조건

  • sec 의 범위는 0 ~ 10,000,000
  • 24시에 도달한 경우, 날짜는 관계없이 0시부터

코드

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Solution {
    public String solution(String time, int sec) {
        
		Matcher matcher = Pattern.compile("(\\w+) (\\d+):(\\d+):(\\d+)").matcher(time);
		if(matcher.find()){ 
            int h = Integer.parseInt(matcher.group(2));
            int m = Integer.parseInt(matcher.group(3));
            int s = Integer.parseInt(matcher.group(4)) + sec;
            if(matcher.group(1).equalsIgnoreCase("pm")){
                h += 12;
            }
            
            m += s/60; s %= 60;
            h += m/60; m %= 60;
            h %= 24;
            
            return String.format("%02d:%02d:%02d", h, m, s);
		}
        
        return "date foramt error";
    }
}