Java에서 분을 시간 및 분 (hh : mm)으로 변환하는 방법


답변:


193

시간이라는 변수에 있다면 t

int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);

더 쉬울 수 없습니다


Java 8로 이것을 달성하는 방법이 Duration있습니까?
IgorGanapolsky

3
경우 t일 수있다 <0(음극)을 제 라인이어야 int minutes = Math.abs(t) % 60;.
wittich

1
또한 시간과 함께 오전 또는 오후를 원하는 경우 다음 조건을 추가하십시오. String amOrPm; if (timeInminutes> = 720) amOrPm = "PM"; else amOrPm = "AM"; 문자열 convertTime = 시간 + ":"+ 분 + amOrPm;
SFAH

오전 / 오후가 아닌 로케일로 어떻게해야합니까? 이것은 부분적이고 지역화되지 않은 솔루션입니다.
ror

29

tl; dr

Duration.ofMinutes( 260L )
        .toString()

PT4H20M

… 또는…

LocalTime.MIN.plus( 
    Duration.ofMinutes( 260L ) 
).toString()

04:20

Duration

java.time 클래스에는 시간 범위를 나타내는 한 쌍의 클래스가 포함됩니다. Duration클래스는 시간 - 분 - 초이며,Period 년 개월-일입니다.

Duration d = Duration.ofMinutes( 260L );

Duration 부속

Duration호출 하여의 각 부분에 액세스to…Part . 이러한 메소드는 Java 9 이상에서 추가되었습니다.

long days = d.toDaysPart() ;
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;

그런 다음 해당 부분에서 고유 한 문자열을 조립할 수 있습니다.

ISO 8601

ISO 8601 표준을 정의는 날짜 - 시간 값에 대한 형식을 텍스트. 타임 라인에 연결되지 않은 시간 범위의 경우 표준 형식PnYnMnDTnHnMnS입니다. P마크 시작하고, T분리 시간 - 분 - 초 년 - 월 - 일. 그래서 한 시간 반은PT1H30M .

java.time 클래스는 기본적으로 문자열 구문 분석 및 생성에 ISO 8601 형식을 사용합니다. DurationPeriod클래스는이 특정 표준 형식을 사용합니다. 그래서 간단히 toString.

String output = d.toString(); 

PT4H20M

다른 형식의 뒷부분 (자바 9에 자신의 문자열을 구축 하지 자바 8) Duration::to…Part방법. 또는 정규식을 사용하여 ISO 8601 형식의 문자열을 조작하려면 이 답변 을 참조하십시오 .

LocalTime

매우 모호하고 혼동되는 시계 형식 대신 표준 ISO 8601 형식을 사용하는 것이 좋습니다 04:20. 그러나 당신이 주장한다면, 당신은 LocalTime클래스 와 함께 해킹하여이 효과를 얻을 수 있습니다 . 기간이 24 시간을 넘지 않으면 작동합니다.

LocalTime hackUseOfClockAsDuration = LocalTime.MIN.plus( d );
String output = hackUseOfClockAsDuration.toString();

04:20


java.time 정보

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date, Calendar,SimpleDateFormat .

Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오. 사양은 JSR 310 입니다.

java.time 클래스는 어디서 구할 수 있습니까?

ThreeTen - 추가 프로젝트 추가 클래스와 java.time를 확장합니다. 이 프로젝트는 java.time에 향후 추가 될 수있는 가능성을 입증하는 근거입니다. 당신은 여기에 몇 가지 유용한 클래스와 같은 찾을 수 있습니다 Interval, YearWeek, YearQuarter, 그리고 .


1
좋습니다. 이와 같은 것을 찾고 있지만 "PT4H20M"또는 "04:20"이 아닌 "4h 20m"또는 "4h 20min"으로 결과를 얻고 싶습니다. 어떤 종류의 서식 지정 방법을 사용해야할까요?
SE 악이기 때문에 aditsu 종료

@aditsuquit 왜냐하면 SEisEVIL Java 9는 Duration::to…Part이 답변에 대한 편집 내용을 보여준 방법을 가져 왔습니다 . 이러한 부분에서 자신 만의 스트링을 쉽게 조립할 수 있습니다.
Basil Bourque

11

당신은 또한 사용할 수 있습니다 TimeUnit 클래스를 . 당신은 정의 할 수 있습니다

private static final String FORMAT = "% 02d : % 02d : % 02d";
다음과 같은 방법을 가질 수 있습니다.

public static String parseTime (long milliseconds) {
      return String.format (FORMAT,
              TimeUnit.MILLISECONDS.toHours (밀리 초),
              TimeUnit.MILLISECONDS.toMinutes (밀리 초)-TimeUnit.HOURS.toMinutes (
              TimeUnit.MILLISECONDS.toHours (밀리 초)),
              TimeUnit.MILLISECONDS.toSeconds (밀리 초)-TimeUnit.MINUTES.toSeconds (
              TimeUnit.MILLISECONDS.toMinutes (밀리 초)));
   }

나는 그것이 받아 들여지는 대답의 코드보다 조금 더 길다는 것을 알고 있지만 IMHO도 더 명확합니다. 나는 이것을 선호한다.
Ole VV

11

java.text.SimpleDateFormat분을 시간과 분으로 변환하는 데 사용

SimpleDateFormat sdf = new SimpleDateFormat("mm");

try {
    Date dt = sdf.parse("90");
    sdf = new SimpleDateFormat("HH:mm");
    System.out.println(sdf.format(dt));
} catch (ParseException e) {
    e.printStackTrace();
}

2

이렇게 할 수 있습니다

        int totalMinutesInt = Integer.valueOf(totalMinutes.toString());

        int hours = totalMinutesInt / 60;
        int hoursToDisplay = hours;

        if (hours > 12) {
            hoursToDisplay = hoursToDisplay - 12;
        }

        int minutesToDisplay = totalMinutesInt - (hours * 60);

        String minToDisplay = null;
        if(minutesToDisplay == 0 ) minToDisplay = "00";     
        else if( minutesToDisplay < 10 ) minToDisplay = "0" + minutesToDisplay ;
        else minToDisplay = "" + minutesToDisplay ;

        String displayValue = hoursToDisplay + ":" + minToDisplay;

        if (hours < 12)
            displayValue = displayValue + " AM";
        else
            displayValue = displayValue + " PM";

        return displayValue;
    } catch (Exception e) {
        LOGGER.error("Error while converting currency.");
    }
    return totalMinutes.toString();

2
ya23

1
통화와 무슨 관련이 있습니까?
fdermishin

2

(Kotlin에서) TextView 또는 다른 것에 대답을 넣으려면 대신 문자열 리소스를 사용할 수 있습니다.

<string name="time">%02d:%02d</string>

그런 다음이 문자열 리소스를 사용하여 다음을 사용하여 런타임에 텍스트를 설정할 수 있습니다.

private fun setTime(time: Int) {
    val hour = time / 60
    val min = time % 60
    main_time.text = getString(R.string.time, hour, min)
}

1

내 프로젝트에이 기능을 사용합니다.

 public static String minuteToTime(int minute) {
    int hour = minute / 60;
    minute %= 60;
    String p = "AM";
    if (hour >= 12) {
        hour %= 12;
        p = "PM";
    }
    if (hour == 0) {
        hour = 12;
    }
    return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}

1

여기에 변환 A에 대한 내 기능입니다 second, millisecondday,hour,minute,second

public static String millisecondToFullTime(long millisecond) {
    return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
}

public static String secondToFullTime(long second) {
    return timeUnitToFullTime(second, TimeUnit.SECONDS);
}

public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
    long day = timeUnit.toDays(time);
    long hour = timeUnit.toHours(time) % 24;
    long minute = timeUnit.toMinutes(time) % 60;
    long second = timeUnit.toSeconds(time) % 60;
    if (day > 0) {
        return String.format("%dday %02d:%02d:%02d", day, hour, minute, second);
    } else if (hour > 0) {
        return String.format("%d:%02d:%02d", hour, minute, second);
    } else if (minute > 0) {
        return String.format("%d:%02d", minute, second);
    } else {
        return String.format("%02d", second);
    }
}

테스팅

public static void main(String[] args) {
    System.out.println("60 => " + secondToFullTime(60));
    System.out.println("101 => " + secondToFullTime(101));
    System.out.println("601 => " + secondToFullTime(601));
    System.out.println("7601 => " + secondToFullTime(7601));
    System.out.println("36001 => " + secondToFullTime(36001));
    System.out.println("86401 => " + secondToFullTime(86401));
}

산출

60 => 1:00
101 => 1:41
601 => 10:01
7601 => 2:06:41
36001 => 10:00:01
86401 => 1day 00:00:01

도움이 되었기를 바랍니다.



-1
long d1Ms=asa.getTime();   
long d2Ms=asa2.getTime();   
long minute = Math.abs((d1Ms-d2Ms)/60000);   
int Hours = (int)minute/60;     
int Minutes = (int)minute%60;     
stUr.setText(Hours+":"+Minutes); 

위의 2는 추정 숫자를 억제합니다
개발자

-1

이 코드를 시도하십시오.

import java.util.Scanner;

public class BasicElement {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int hours;
        System.out.print("Enter the hours to convert:");
        hours =input.nextInt();
        int d=hours/24;
        int m=hours%24;
        System.out.println(d+"days"+" "+m+"hours");     

    }
}

2
몇 분에서 몇 분까지
keyser

-1

초 단위로 입력하면 다음과 같이 hh : mm : ss 형식으로 변환 할 수 있습니다.

int hours;
int minutes;
int seconds;
int formatHelper;

int input;


//formatHelper maximum value is 24 hours represented in seconds

formatHelper = input % (24*60*60);

//for example let's say format helper is 7500 seconds

hours = formatHelper/60*60;
minutes = formatHelper/60%60;
seconds = formatHelper%60;

//now operations above will give you result = 2hours : 5 minutes : 0 seconds;

입력이 86400 초 (24 시간) 이상일 수 있으므로 formatHelper를 사용했습니다.

입력의 총 시간을 hh : mm : ss로 표시하려면 formatHelper를 피할 수 있습니다.

도움이 되었기를 바랍니다.


1
작동하지 않습니다. 경우 input7500이며, 결과는 분명 잘못이다, 7,500시간 5 분 0 초입니다. 그리고 질문은 초를 전혀 언급하지 않았습니다.
fdermishin

@fdermishin이 정확합니다. 온라인으로 시도하십시오!
Calculuswhiz

-1
int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);

1
왜 정수 형식으로 사용하는 %d포맷 스트링 값 "" +mHours"" +mMinutes?
fdermishin 2012

-1
import java.util.Scanner;
public class Time{
    public static void main(String[]args){
        int totMins=0;
        int hours=0;
        int mins=0;
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter the time in mins: ");
        totMins= sc.nextInt();
        hours=(int)(totMins/60);
        mins =(int)(totMins%60);
        System.out.printf("%d:%d",hours,mins);
    }
}

이것이 허용되는 답변과 어떻게 다른가요?
fdermishin
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.