자바에서 분을 시간과 분으로 변환해야합니다. 예를 들어 260은 4:20이어야합니다. 누구든지 그것을 변환하는 방법을 도울 수 있습니까?
자바에서 분을 시간과 분으로 변환해야합니다. 예를 들어 260은 4:20이어야합니다. 누구든지 그것을 변환하는 방법을 도울 수 있습니까?
답변:
시간이라는 변수에 있다면 t
int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);
더 쉬울 수 없습니다
Duration있습니까?
t일 수있다 <0(음극)을 제 라인이어야 int minutes = Math.abs(t) % 60;.
Duration.ofMinutes( 260L )
.toString()
PT4H20M
… 또는…
LocalTime.MIN.plus(
Duration.ofMinutes( 260L )
).toString()
04:20
Durationjava.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 표준을 정의는 날짜 - 시간 값에 대한 형식을 텍스트. 타임 라인에 연결되지 않은 시간 범위의 경우 표준 형식 은 PnYnMnDTnHnMnS입니다. P마크 시작하고, T분리 시간 - 분 - 초 년 - 월 - 일. 그래서 한 시간 반은PT1H30M .
java.time 클래스는 기본적으로 문자열 구문 분석 및 생성에 ISO 8601 형식을 사용합니다. Duration및 Period클래스는이 특정 표준 형식을 사용합니다. 그래서 간단히 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의 프레임 워크는 나중에 자바 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, 그리고 더 .
Duration::to…Part이 답변에 대한 편집 내용을 보여준 방법을 가져 왔습니다 . 이러한 부분에서 자신 만의 스트링을 쉽게 조립할 수 있습니다.
당신은 또한 사용할 수 있습니다 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 (밀리 초)));
}
이렇게 할 수 있습니다
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();
내 프로젝트에이 기능을 사용합니다.
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;
}
여기에 변환 A에 대한 내 기능입니다 second, millisecond에day,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
도움이 되었기를 바랍니다.
Minutes mod 60은 남은 분과 함께 시간을 제공합니다.
이 코드를 시도하십시오.
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");
}
}
초 단위로 입력하면 다음과 같이 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를 피할 수 있습니다.
도움이 되었기를 바랍니다.
input7500이며, 결과는 분명 잘못이다, 7,500시간 5 분 0 초입니다. 그리고 질문은 초를 전혀 언급하지 않았습니다.
int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);
%d포맷 스트링 값 "" +mHours과 "" +mMinutes?
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);
}
}