소소한 개발 공부

[C#] 초(sec)를 시간 형식으로 바꾸기 본문

개발/Unity

[C#] 초(sec)를 시간 형식으로 바꾸기

이내내 2022. 8. 18. 14:44

1. static 클래스를 붙여 사용하기

public static class TimeStringFormatter {

    public static string Sec2Time(int secValue) {
        string time = string.Empty;
        if (secValue / 3600 > 0)
        {
            time = string.Concat(time, (secValue/3600).ToString(), " 시간 ");
            secValue = secValue % 3600;
        }
        if (secValue / 60 > 0)
        {
            time = string.Concat(time, (secValue/60).ToString(), " 분 ");
            secValue = secValue % 60;
        }
        if (secValue % 60 >= 0)
        {
            time = string.Concat(time, (secValue%60).ToString(), " 초 ");
        }
        return time;
    }
}

사용 예시

Debug.Log("시간 : " + TimeStringFormatter.Sec2Time(100000));

결과

 

 

2. this 를 사용하여 int 값 바로 뒤에서 사용하는 방법

public static class TimeStringFormatter {

    public static string Sec2Times(this int secValue) {
        string time = string.Empty;
        if (secValue / 3600 > 0)
        {
            time = string.Concat(time, (secValue/3600).ToString(), " 시간 ");
            secValue = secValue % 3600;
        }
        if (secValue / 60 > 0)
        {
            time = string.Concat(time, (secValue/60).ToString(), " 분 ");
            secValue = secValue % 60;
        }
        if (secValue % 60 >= 0)
        {
            time = string.Concat(time, (secValue%60).ToString(), " 초 ");
        }
        return time;
    }
}

- 매개변수 자료형 앞에 this를 붙여주기

 

사용 예시

Debug.Log(10000.Sec2Times());

결과